Is there any way to search for a given string in the last, say, 500 lines of a text file in Python ?
How do we do that ?
Thank you !
Is there any way to search for a given string in the last, say, 500 lines of a text file in Python ?
How do we do that ?
Thank you !
You could do something like this:
Reads the file, split it in lines, get the last 500 lines.
lines = open("file.txt", "r").readlines()[-500:]
then search
for line in lines:
if "WHAT I SEARCH" in line:
print "Found in line: ", line
or
if "WHAT I SEARCH" in "\n".join(lines):
print "Found"
You could also find a way not to read the full file but just the end of it (with seek and read).