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
In the following technique:
text
.text
is then split into sections using 'bring it on'
as a keywordlast_section
is selected using [-1]
last_section
into lines using \n
as as keyworderr
in them and append them to the errors
listerrors
listwith 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)
[err] - there is no way
err - back