python - 读取大文本文件的下一行
问题描述
我是 python 新手。我有一个巨大的文本文件(大约 15gb),所以不可能读完所有的行,我在这里读过如何解决这个问题。现在谈谈我的问题。是否可以在不跳转到循环开头的情况下读取 for 循环中的下一行。
这就是我的意思
with open(input) as infile:
for line in infile:
print("current line: ",line)
#reading next line
print("this is the second line ", line)
#jumping back to the beginning and working with the 3rd line
当我的文字看起来像这样时。
1st line
2nd line
3rd line
4th line
5th line
6th line
7th line
我希望输出是这样的
current line: 1st line
this is the second line: 2nd line
current line: 3rd line
this is the second line: 4th line
...
解决方案
您可以使用iter()
and来执行此操作next()
。
with open('text.txt') as infile:
iterator = iter(infile)
for line in iterator:
print("current line:",line)
print("this is the second line", next(iterator, "End of File"))
给定输入文件:
A
B
C
D
E
它输出:
current line: A
this is the second line B
current line: C
this is the second line D
current line: E
this is the second line End of File
推荐阅读
- python - python 2.7中的打印语句旁边是否可以有一个.join函数和一个%(var)?
- node.js - 如何将数据库查询从模型传递到 Express.js 中的控制器
- python - 使用 python 脚本在 GDB 中写入程序的输入流
- jetty - 如何使用外部 ssl 卸载在 HTTP2 中配置 Jetty
- python - 无法使用 Select 小部件初始化 Bokeh 仪表板
- amazon-web-services - AssociateVPCWithHostedZone 使用 Lambda 和 Boto3 时访问被拒绝错误
- email - 如何使用 eiffel 内核库发送电子邮件
- mongodb - Mongodb查询解释opterationTime的含义?
- jetty - 如何在 Jetty 中监控服务器套接字
- actionscript-3 - 进入下一帧时停止声音 - Adobe Animate/AS3