Read file from bottom

David LeBlanc whisper at oz.net
Mon May 13 17:38:39 EDT 2002


I'd do it something like this:

# tail.py

buff = ''
chunksize = 500                 #your choice
myFile = file('news.txt', 'r')  #python 2.2 file object
myFile.seek((-chunksize), 2)    #seek to eof - chunksize bytes. "2" means
relative to EOF

#dump version
#buff = myFile.read(chunksize)  #hopefully file length is > chunksize
#print buff

#by line version
done = False
while not done:
    buff = myFile.readline()
    if buff:
        print buff
    else:
        done = True

#note the first line printed will probably be a partial, so you might want
to
#not print it.

David LeBlanc
Seattle, WA USA

> -----Original Message-----
> From: python-list-admin at python.org
> [mailto:python-list-admin at python.org]On Behalf Of William Park
> Sent: Monday, May 13, 2002 13:40
> To: python-list at python.org
> Subject: Re: Read file from bottom
>
>
> Julia Bell <julia.bell at jpl.nasa.gov> wrote:
> > I'm currently using
> >    line = input_handle.readline()
> > to read individual lines from an input file; however, I'm only generally
> > interested in the last few lines of the line (not the preceeding several
> > thousand lines).
> >
> > Is there an efficient (and relatively easy - I'm new to Python) way of
> > reading the file from the last line backward instead of the first line
> > forward?
> >
> > (I do not want to read the entire file using readlines because it could
> > overwhelm the memory.)
>
> tail | python script.py
>
> --
> William Park, Open Geometry Consulting, <opengeometry at yahoo.ca>
> 8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin
> --
> http://mail.python.org/mailman/listinfo/python-list






More information about the Python-list mailing list