A bug with file.tell()?
Nick Craig-Wood
nick at craig-wood.com
Fri Sep 10 04:30:02 EDT 2004
Nick Jacobson <nicksjacobson at yahoo.com> wrote:
> Is this a bug?
>
> This code involves the file methods "seek" and "tell". Even though
> the file pointer is in the middle of the file, "tell" returns a
> position at the end of the file!
Its something to do with buffering when using the file() as an
iterator.
> fp = file("test.txt")
> #read in some of the file:
> for line in fp:
> if line == "blah3\n":
> break
> fpos = fp.tell() #save the current position...
>
> for line in fp:
> print line #prints "asdf", so it wasn't at the end of the file
>
> fp.seek(fpos) #rewind?
> for line in fp:
> print line #prints nothing, because it's at the end of the file!
>
>
> The test.txt file is:
> blah1
> blah2
> blah3
> asdf
If you re-write your loop using this equivalent code :-
#...
while 1:
line = fp.readline()
if line == "": # EOF
break
if line == "blah3\n":
break
#...
You'll find it works fine.
IMHO this is a bug - even with buffering tell() should give where the
file returned data to the user not where its read data from the file.
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list