How do i read just the last line of a text file?

Terry Reedy tjreedy at udel.edu
Sun May 29 11:30:07 EDT 2005


"Andy Leszczynski"
> What if a file is long enough?

I believe you meant "What if a file is too long to read all into memory at 
once?"

If the file is randomly accessible (with file.seek() backwards from the 
end) then you can read a chunk at the end that you expect to be large 
enough to contain the last line and search backwards for \n (ignoring a 
terminating \n) to find the end of the next-to-last line.  Even if the file 
will fit in memory, this may be faster.

Terry J. Reedy






More information about the Python-list mailing list