How to read lines only at the end of file?
Alex Martelli
aleax at aleax.it
Fri Nov 7 08:41:45 EST 2003
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.
Alex
More information about the Python-list
mailing list