How to find the beginning of last line of a big text file ?

Sebastian Bassi sbassi at clubdelarazon.org
Thu Jan 1 11:54:44 EST 2009


On Thu, Jan 1, 2009 at 2:19 PM, Barak, Ron <Ron.Barak at lsi.com> wrote:
> I have a very big text file: I need to find the place where the last line
> begins (namely, the offset of the one-before-the-last '\n' + 1).
> Could you suggest a way to do that without getting all the file into memory
> (as I said, it's a big file), or heaving to readline() all lines (ditto) ?

for line in open(filename):
    lastline = line
print "the lastline is: %s",%lastline

This will read all the lines, but line by line, so you will never have
the whole file in memory.
There may be more eficient ways to do this, like using the itertools.

Best,
SB.



More information about the Python-list mailing list