0

Here's a sample code

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)

How to write line 5 in this code ?

user3483203
  • 50,081
  • 9
  • 65
  • 94
T.Galisnky
  • 79
  • 1
  • 11
  • Alternatively, instead of looking back, make a note when a line contains your string and check whether the next one does, too. – Reti43 Feb 17 '18 at 17:48

1 Answers1

1

Save the previous line at each iteration:

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

Sample input:

hello
no
no
hello

Output:

no  
user3483203
  • 50,081
  • 9
  • 65
  • 94