使用Python迭代文件时,请参阅上一行

时间:2015-06-17 15:49:07

标签: python

我有一个如下的循环:

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

1 个答案:

答案 0 :(得分:4)

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

只需将当前行存储在变量中;它将成为下一次迭代的前一个:

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