Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading