python - 从文件中读取行作为移位寄存器,在 Python 中有两个单元格

标签 python

我需要以这样的方式读取文件的行,这种方式将表现为具有两个单元格的移位寄存器。 例如:

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/

相关文章:

python - 如何在 Python Tools for Visual Studio 中运行 Django manage.py 命令?

python - raw_input 时间有限?

javascript - 如何实现我的 JavaScript 表单想法?

python - 你能把两个不同长度的独立字典相乘来创建第三个吗?

python - 使用 mechanize 检索 robots.txt 时出现 HTTP 403 错误

python解码原始udp数据包的正确方法

python - 如何从 Bitmex Websocket API ws.recent_trades() 日志中提取单独且独特的实时交易

python - 我的 Python3 HTTP 头解析代码可以吗?

python - 在centos 6.x 上使用python3 安装twis​​ted 失败?

python - Matplotlib:外部图例,分布在多个子图中