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

2024-05-16 14:28:26 发布

您现在位置: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

Tags: 代码in内容foraswithlineopen