Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read a text file line by line and check for a substring on 2 of the lines

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.

like image 601
magicsword Avatar asked Mar 01 '23 11:03

magicsword


1 Answers

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 ""
like image 69
tdelaney Avatar answered May 01 '23 08:05

tdelaney