Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在读取文本文件时,使用文件循环中的for行,如何选择前一行?_Python_Python 3.x - Fatal编程技术网

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

Python 在读取文本文件时,使用文件循环中的for行,如何选择前一行?,python,python-3.x,Python,Python 3.x,下面是一个示例代码 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:

下面是一个示例代码

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

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

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  

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