How to read lines only at the end of file?

Christopher Koppler klapotec at chello.at
Fri Nov 7 10:17:18 EST 2003


On Fri, 07 Nov 2003 13:41:45 GMT, Alex Martelli <aleax at aleax.it>
wrote:

>Batista, Facundo wrote:
>
>> Christopher Koppler wrote:
>> 
>> #- You could do the following:
>> #-
>> #- >>> f = file('filename.txt', 'r')
>> #- >>> numberoflines = 10
>> #- >>> for line in f.readlines()[-numberoflines:]:
>> #- ...     print line
>> #-
>> #- which prints the last 10 lines of the file.
>> 
>> But if the file has 2GB? This method doesn't reads *all* the file?
>
>Yes: f.readlines() does read all of the file.
>
>You can use f.seek to position yourself at some distance
>from the _end_ (in bytes, though) and .readlines() from there --
>but if the last N lines are abnormally long you're still not
>guaranteed to be able to give the last N lines without reading
>all of the file, worst case.

A quick search through the online cookbook finds
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157035.


--
Christopher




More information about the Python-list mailing list