[Tutor] Trying to extract the last line of a text file

Luke Paireepinart rabidpoobear at gmail.com
Fri Oct 20 02:25:02 CEST 2006

Chris Hengge wrote:
> I thought my solution was the easiest.. but I guess everyone skipped it =P
No, we didn't skip it,
but as we're all programmers here, we showed alternate ways that it 
could be done.
Your post is the one that sparked the whole 'garbage collection' thing, 
you'll notice.

Now, I don't want to be left out of the loop on this,
and the first thing I thought of when I read his question about how to 
read the last line was:
Well, what if he wants to read the last line of 100 20 mb files?
Does he really want to read all of these into memory just to get the 
last line?
I wouldn't think so!
So I've made an alternate solution using seek.
The last line can't be more than 1000 chars long, or whatever the Python 
maximum recursion depth happens to be at runtime,
but you could easily change this into a non-recursive implementation if 
you so desired.
I just wanted to be cool :)

f = file('wii.txt','r')
f.seek(-1,2)#start at end of file.
if f.read(1) == '\n':#if file ends with a newline:
    f.seek(-3,1)#start at right before the newline.
    f.seek(-1,1)#just start at the end.
def prevchar(fileobj):
    achar = fileobj.read(1)
    if achar == '\n': return ''
        return prevchar(fileobj)+achar
print prevchar(f)

More information about the Tutor mailing list