I have a very large text file. I want to search for the last occurrence of a specific word and then perform certain operations on the lines that follows it.
I can do something like:
if "word" in line.split():
do something
I am only interested in the last occurrence of "word"
however.
Well an easier and quicker solution would be to open the file in reversed order and then searching the first word location.
In python 2.6 you can do something like (where word is string you are looking for)
for line in reversed(open("filename").readlines()):
if word in line:
# Do the operations here when you find the line
Try like this:
f = open('file.txt', 'r')
lines = f.read()
answer = lines.find('word')
and then you can pick the last word from this
You may also use str.rfind
str.rfind(sub[, start[, end]])
Return the highest index in the string where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With