Python 在读取文本文件时,使用文件循环中的for行,如何选择前一行?
下面是一个示例代码Python 在读取文本文件时,使用文件循环中的for行,如何选择前一行?,python,python-3.x,Python,Python 3.x,下面是一个示例代码 with open('somefile.txt', 'r') as file: for line in file: find = 'some string' if find in line: if previous line is the same as this line: #how to write this ? pass else:
with open('somefile.txt', 'r') as file:
for line in file:
find = 'some string'
if find in line:
if previous line is the same as this line: #how to write this ?
pass
else:
print(line)
如何在此代码中写入第5行?在每次迭代时保存前一行:
with open('test.txt', 'r') as file:
previous = None
find = 'n'
for line in file:
if find in line:
if line != previous:
print(line)
previous = line
样本输入:
hello
no
no
hello
输出:
no
或者,不要回头看,而是在一行包含字符串时做一个记录,并检查下一行是否也包含字符串。