1

Possible Duplicate:
Get last n lines of a file with Python, similar to tail

Hello,

How can I have Python return the last n lines of a file without reading it line by line?

smci
  • 29,564
  • 18
  • 109
  • 144
Escualo
  • 38,824
  • 20
  • 81
  • 128
  • This is a duplicate: http://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail – Nicholas Riley Jan 26 '10 at 00:37
  • Did not see the duplicate. Thanks (will close). – Escualo Jan 26 '10 at 00:39
  • This title says one thing (read the file backwards), but its details and the duplicate link say another (just read the last n line tail). Title needs to be fixed otherwise this messes up canonicals. – smci Apr 24 '18 at 23:06

1 Answers1

1

Something like this:

  • Use seek() to get something like the last 4096 bytes of a file.
  • See how many newlines you have in those bytes. If you have n or more, then you're done. If you have fewer, then read the previous 4096 bytes until you're done.

Not sure if there's a built-in way to do this.

Claudiu
  • 216,039
  • 159
  • 467
  • 667