使用Python遍历文件时,请参考上一行。 - python

This question already has answers here:

Iterate a list as pair (current, next) in Python

(10个答案)

5年前关闭。

我有一个如下循环:

with open(file, 'r') as f:
    next(f)
    for line in f:
        print line

但是我不想每次迭代都只打印当前行,我也想像下面一样打印前一行,但是代码没有给我我想要的东西:

with open(file, 'r') as f:
    next(f)
    for line in f:
        previous(f)    #this does not go to the previous line
        print line
        next(f)
        print line
        next(f)

结果应该是这样的:

输入:

line1
line2
line3

输出:

line1
line2
line2
line3

python大神给出的解决方案

迭代器只能前进,因此没有previous()函数。

只需将当前行存储在变量中即可;它将是下一个迭代的前一个:

with open(file, 'r') as f:
    previous = next(f)
    for line in f:
        print previous, line
        previous = line