gpt4 book ai didi

python 读取文件 next()

转载 作者:行者123 更新时间:2023-12-05 09:22:41 25 4
gpt4 key购买 nike

为我糟糕的编程道歉,因为我是一个糟糕的程序员。我引用:How to access next line in a file(.txt) in Python在问题实例中,next() 模块能够读取下一行。但是,一旦代码返回到 for 循环,它就不是“下一行”,而是下一行。

输入:

a /n
b /n
c /n
d /n

输出:

This line contains a, next line contains b.
This line contains c next line contains d.

是否有可能达到这样的结果

This line contains a, next line contains b
This line contains b next line contains c

编辑-抱歉忘记输入代码-示例代码:

a = open('file.txt','rb')
for i in a:
b = next(a)
print "this line contains %s, next line contains %s" %(a,b)
a.close()

最佳答案

您可以使用文件对象的 readlines 方法来制作文件行的列表。

由于每行末尾都有一个换行符,如果您希望将其打印在后面跟有其他文本的单行上,则需要删除它。您可以使用字符串对象的 strip 方法来删​​除字符串的尾随字符。

当遍历这些行时,您可以通过将索引增加 1 来访问列表中的下一行。

而且我发现在创建文件对象时最好使用 with open(...) as file_name: 语法,因为它会自动为您关闭文件。

with open('file.txt', 'rb') as text_file:
lines = [line.strip() for line in text_file.readlines()]
for index, line in enumerate(lines):
# Check for last line
try:
next_line = lines[index + 1]
except IndexError:
print("this line contains %s, and is the end of file." % line)
else:
print("this line contains %s, next line contains %s" % (line, next_line))

关于python 读取文件 next(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25031393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com