I want to read a text file and check for strings
with open(my_file,'r') as f:
for line in f:
if 'text1' in line:
f.next()
if 'text2' in line:
# do some processing
I want to first find the text 'text1' at the beginning of the line then if found I want to check the next line for 'text2' if found then I will do some other processing. Appears that the f.next() is not moving to the next line.
Use the for loop iteration and use a state variable to decide whether you are in the "test1" case. That way you don't have to juggle a separate StopIteration
exception.
text1_line = ""
with open(my_file) as f:
for line in f:
if text1_line and 'text2' in line:
# do some processing
text1_line = ""
continue
text1_line = line if 'text1' in line else ""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With