Python: printing a line if a certain line comes after it

Lets say I have a .txt file which reads

this is line x  
this is line y  
this is line x 
this is line x  
this is line x  
this is line y   
this is line x  
this is line x  
this is line y

I want to print ‘this is line x’ only if ‘this is line y’ comes after it (so in this example it should only print 3 times).

I’ve tried:

skip_line = True  
with open("input_n.txt","r") as myfile:
     for line in myfile:
        if "x" in line:
            skip_line = False
        elif "y" in line:
            skip_line = True
        else:
            pass
        if skip_line:
            continue
        print(line)

However this prints every ‘this is line x’ anyway I can see in my code that it does this because I do skip_line = false for x in the string, so how can I make it print the three times I actually want it to?

>Solution :

You need to track the previous line with your bool. Save it with another var.

 skip_line = True
 for line in myfile:
    if "x" in line:
        next_skip_line = False
    elif "y" in line:
        next_skip_line = True
    else:
        pass
    if skip_line:
        skip_line = next_skip_line
        continue
    else:
        skip_line = next_skip_line
        print(line)

Leave a Reply