在读取文本文件时,使用文件循环中的for行,如何选择前一行?

2024-04-25 19:49:49 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一个示例代码

with open('somefile.txt', 'r') as file:
    for line in file:
        find = 'some string'
        if find in line:
            if previous line is the same as this line: #how to write this ?
                pass
            else:
                print(line)

如何在这段代码中写第5行?你知道吗


Tags: 代码intxt示例forifaswith
1条回答
网友
1楼 · 发布于 2024-04-25 19:49:49

在每次迭代时保存前一行:

with open('test.txt', 'r') as file:
    previous = None
    find = 'n'
    for line in file:
        if find in line:
            if line != previous:
                print(line)
        previous = line

样本输入:

hello
no
no
hello

输出:

no  

相关问题 更多 >