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

Question:

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?

Asked By: Kish Kharka

||

Answers:

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

skip_line = True
prev_line = ""
with open("f.txt","r") as myfile:
    skip_line = True
    for line in myfile:
        if "x" in line:
            next_skip_line = False
        elif "y" in line:
            next_skip_line = True

        # skip_line is False if the last line was x
        # next_skip_line is True if this line was y
        if not skip_line and next_skip_line:
            print(prev_line)
        prev_line = line
        skip_line = next_skip_line
Answered By: Shaun Ramsey
#using a list to dummy the txt file read line by line
lst = [
    "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"
]

store = ""
for line in lst:
    if "y" in line and store:
        print(store)
    elif "x" in line:
        store = line

With this, it will only print if the current line contains "y" and a previous line exists.

Answered By: Shorn
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.