首页 > 解决方案 > 读取大文本文件的下一行

问题描述

我是 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
...

标签: pythonfileiteration

解决方案


您可以使用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

推荐阅读