我需要以这样的方式读取文件的行,这种方式将表现为具有两个单元格的移位寄存器。 例如:
with open("filename", 'r') as file:
--first iteration--
present = line1
next = line2
do something
--second iteration--
present = line2
next = line3
do something
--third iteration--
present = line3
next = line 4
do someting
and so on....
这可以通过 open(file, 'r')
完成,但它不能保证文件会被关闭,因为脚本可能会停止
由于在最后一次迭代之前“做某事”。
有什么优雅的方法吗?
最佳答案
当然:
with open("filename", 'r') as file:
current_line = next(file) # Get 1st line, advance iterator to 2nd line
for next_line in file:
do_something(current_line, next_line)
current_line = next_line
关于python - 从文件中读取行作为移位寄存器,在 Python 中有两个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23823280/