search a string in a text file after a particular string in python

Question:

Suppose this is the text file which has 10 line content.

1 mpe:p01 
2 mpe:p02 
3 * xyz 3 
4 mpe:p04 
5 mpe:p05 
6 mpe:p06 
7 mpe:p07 
8 mpe:p08 
9 mpe:p09 
10 mpe:p100 

I need to search string "mpe:" after "xyz" string.

My piece of code is:

str1_name ="* xyz"  
str2_name = "mpe:" ` 

lines = [] 

with open("textfile.txt",'r') as f:
   for line in f:
       if str2_name in line:
           lines.append(line)  
        lines2=lines[0]  
    print(lines2)

it is giving me output:

1 mpe:p0

but I want the output:

4 mpe:p0

Asked By: Yash K

||

Answers:

lines = []
line_after_str1=[]

str1_name ="* xyz"

str2_name = "mpe:" 

with open("textfile.txt",'r') as f:
    all_lines=f.readlines()
    for line in range(len(all_lines)):
        
        if str1_name in all_lines[line]:
            line_after_str1.append(all_lines[line+1].replace('n',''))
        elif str2_name in all_lines[line]:
            lines.append(all_lines[line].replace('n',''))
        

print(line_after_str1)

Output:

['4 mpe:p04']
Answered By: Ali Adhami

You need to check if you encountered string xyz first. If you did, then set a flag to true. Then continue reading file. If previous line read was xyz, the flag would have been set to True. Check if current line has mpe and append that line to lines. See if this code works.

str1_name ="* xyz"  
str2_name = "mpe:" 
prev_xyz = False

lines = [] 

with open("textfile.txt",'r') as f:
    for line in f:
       if str2_name in line and prev_xyz:
           lines.append(line.strip())  
           #lines2=lines[0] prev line will strip out n
       if str1_name in line:
           prev_xyz = True
       else:
           prev_xyz = False
print(lines)

Output:

['4 mpe:p04']
Answered By: Joe Ferndz

Well, if you’re sure mpe follows xyz, you could run something like:

str1_name ="* xyz"  

with open("textfile.txt",'r') as f:
    for line in f:
        while str1_name not in line:
            pass
        if str2_name in line:
            print(next(f))

If the searched string doesn’t follow immediately :

str1_name ="* xyz"
str2_name = "mpe:"  

checkpoint = False

with open("textfile.txt",'r') as f:
    for line in f:
        if str1_name in line:
            checkpoint = True
        if checkpoint and str2_name in line:
            print(line)
            break
Answered By: Bastien Harkins
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.