efficient 'tail' implementation

Marius Gedminas mgedmin at gmail.com
Thu Dec 15 10:57:51 CET 2005


Magnus Lycka wrote:
> To read the last x bytes of a file, you could do:
>
>  >>> import os
>  >>> x = 2000 # or whatever...
>  >>> f=open('my_big_file')
>  >>> l=os.fstat(f.fileno()).st_size
>  >>> f.seek(l-x)
>  >>> f.read()

You don't need fstat/st_size, you can ask seek to move to an offset
relative to the end of the file:

>>> x = 2000
>>> f = open('my_big_file')
>>> f.seek(-x, 2)
>>> f.read()




More information about the Python-list mailing list