File Reading , Reverse Direction

Ratnakar Malla rmalla1 at lsu.edu
Fri Jul 27 02:22:43 EDT 2001


Hi,
Thanx for the lightning reply.
Well , sorry for not speciying my platform. It is a pentium , running
Windows 2000.
what I really wanted was some sort of "tail " kind of functionality.
Unfortunately, there is no "tail" command in Windows. I was just wondering,
if there is any better way than reading the entire file into memory.
Anyways thanx for your reply. I am sticking with readlines()
Cheers,
Ratnakar

Peter Hansen wrote:

> Ratnakar Malla wrote:
> >
> > Hi,
> > I need to read from a very long file. But the only information I am
> > interested is
> > 2 lines at the bottom of the file.
>
> > 1) Can i read the file in the reverse direction , so that I dont lose
> > time?
>
> Do you really want to read in "reverse"?  To me that implies getting
> each byte in reverse order, which would require reversing the lines
> again after finding the "first" two... Or do you just want to read
> line-by-line, in reverse?
>
> > 2) If so how??
>
> How about this?
>
>    lastTwoLinesAsList = open('somefile').readlines()[-2:]
>
> > 3) I tried the normal way, but looks like, it is taking lot of time.
>
> What is "normal"?  Maybe your code is not the most efficient
> implementation...
>
> You could also use "seek" to find the end of the file, then
> go backwards a few dozen bytes at a time, grabbing blobs of
> data until you found the third-last newline (or the second last,
> if the file did not end with a newline), then return everything
> after that point.  This would be awkward, largely unreadable,
> bug-prone, and might take a while to develop.
>
> Or how about calling out to "tail"?
>
>    import os
>    lastTwoLinesAsString = os.popen('tail -2 somefile').read()
>
> You might also want to post a sample of your code, and mention
> which platform you are on, so feedback might be a little more
> relevant to your situation...
>
> --
> ----------------------
> Peter Hansen, P.Eng.
> peter at engcorp.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: rmalla1.vcf
Type: text/x-vcard
Size: 294 bytes
Desc: Card for Ratnakar Malla
URL: <http://mail.python.org/pipermail/python-list/attachments/20010727/af3c506a/attachment.vcf>


More information about the Python-list mailing list