[Tutor] Reset while loop

Alan Gauld alan.gauld at btinternet.com
Wed May 6 15:05:27 CEST 2009


"Alan Gauld" <alan.gauld at btinternet.com> wrote

>>         f.seek(0, 2)
>>         pos, tailsize = divmod(f.tell(), bufsize)
>>         if tailsize == 0:
>>             pos = max(0, pos-1)
>>         pos *= bufsize
>>         f.seek(pos)
>
> I got confused trying to work out exactly what this was doing.
> pos is initially the number of times bufsize fits in the file, but
> then gets modified to zero or one less than its current value.

I had another look during a cup of coffee and what I think you
are doing is positioning the cursor up to buffsize away from
the end of the file?

If so I think this is easier:

f.seek(0, os.SEEK_END)      # goto end of file
offset = f.tell() % buffsize       #  trim off N buffers worth
if offset == 0:                           # if no tail backup one buffers 
worth
    offset = buffsize
f.seek(-offset, os.SEEK_END)      # goto beginning of tail

If I misunderstood I'm sure someone will say! :-)

OTOH since you only use the last two lines why not miss all
that out and go straight to where you want to be with:

f.seek(-buffsize, os.SEEK_END)    # goto one buffsize away from end
return f.read().split(linesep)[-2:]

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list