Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the last occurrence of a word in a large file with python

Tags:

python

text

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.

like image 726
hat Avatar asked Dec 05 '22 06:12

hat


2 Answers

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
like image 73
harshadbhatia Avatar answered Dec 08 '22 04:12

harshadbhatia


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.

like image 37
Rahul Tripathi Avatar answered Dec 08 '22 04:12

Rahul Tripathi