Home > Software engineering >  How to print rows with specific string onwards based on the last occurrence of a string in the file
How to print rows with specific string onwards based on the last occurrence of a string in the file

Time:12-10

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

CodePudding user response:

In the following technique:

  • The text file is opened, read and assigned to variable text.
  • text is then split into sections using 'bring it on' as a keyword
  • The last_section is selected using [-1]
  • Split the last_section into lines using \n as as keyword
  • Find the lines that contain the word err in them and append them to the errors list
  • print the errors within the errors list
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
  • Related