为我糟糕的编程道歉,因为我是一个可怕的程序员。我参考: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()
答案 0 :(得分:3)
您可以使用文件对象的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))
答案 1 :(得分:1)
您可以通过将所有行读入字符串列表来解决您的问题。
a = open('file.txt','rb')
text_as_list = a.readlines()
for idx in range(len(text_as_list)-1):
print "this line contains %s, next line contains %s" %(text_as_list[idx], text_as_list[idx+1])
a.close()
答案 2 :(得分:1)
a = open('file.txt','rb')
prev=a.next()
for i in a:
print "this line contains %s, next line contains %s" %(prev,i)
prev=i
a.close()
答案 3 :(得分:1)
我认为这样做。但是,您应该考虑更改输出的顺序。通常,您希望先输出当前行,然后输出前一行,因为这是读取文件的顺序。因此,解决方案可能会有点混乱。如果你愿意,可以给一个upvote: - )
a = open('text.txt','rb')
current_line = " "
previous_line = " "
while (previous_line != ""):
# In the first step, we continue and do nothing to read the next line so
# we have both lines.
if current_line == " " and previous_line == " ":
# Get the first line.
current_line = a.readline()
continue
# Update the lines.
previous_line = current_line
current_line = a.readline()
# No output if the next line does not exist.
if current_line == "":
break
# Output.
print "This line contains " + previous_line[0] + ", next line contains " + current_line[0]
a.close()