0

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 !

  • duplicate of http://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail – lordkain Feb 25 '14 at 10:51

1 Answers1

0

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).

Nicolas Defranoux
  • 2,646
  • 1
  • 10
  • 13