【问题标题】:While reading a text file, using a for line in file loop, how to select the previous line? [duplicate]在读取文本文件时,在文件循环中使用 for 行,如何选择上一行? [复制]
【发布时间】:2018-02-17 17:44:16
【问题描述】:

这是一个示例代码

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 行?

【问题讨论】:

  • 或者,不要回头看,而是在一行包含您的字符串时记下,并检查下一行是否也包含。

标签: python python-3.x


【解决方案1】:

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

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  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 2013-10-04
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多