pythonpython-3.xfilensregularexpression

How to print rows with specific string onwards based on the last occurrence of a string in the file using python


I have a text file com.txt and the content of that text file is shown below. There are many occurrences of a string bring it on in it and the program should be able to find the last occurrence of this string bring it on and print only those lines after the last occurrence onward that have a string [err].

a = 'bring it on'

com.txt

Error logs are useful in many respects.
bring it on
A network or system administrator can resolve errors more quickly and easily with the information available
from the error logs
bring it on
[err] - not found
Error logs also could provide insights on ha
bring it on
cooll in this way
[err] - there is no way
hopefully
err - back
success

Now the program should be able to find the last occurrence of a string a and find and print only those lines which have a string err after the last occurrence of a string a so the output would be only those lines that have a string err after the last occurrence of a string a

[err] - there is no way
err - back

I tried below code

with open('com.txt', 'r') as file_:
  line_list = list(file_)
  line_list.reverse()

  for line in line_list:
    if line.find(a) != -1:
      # do something
      print(line)

It is giving below output

bring it on
bring it on
bring it on

Expected output: find and print only those lines which have a string err after the last occurrence of a string a

[err] - there is no way
err - back

Solution

  • In the following technique:

    with open('com.txt', 'r') as file_:
        text = file_.read()
    
    last_section = text.split('bring it on')[-1]
    
    errors = [line for line in last_section.split('\n') if 'err' in line]
    
    for error in errors:
        print(error)
    

    Output:

    [err] - there is no way
    err - back