for line in ftpr: and fptr.tell()

Erik Max Francis max at alcyone.com
Mon Nov 3 23:20:13 EST 2003


Jamey Cribbs wrote:

> Because you won't get the correct file position from tell().  I think
> it
> had something to do with the file iterator caching several kb of the
> file when it first started the for loop.
> 
> Is there a fix/work-around for this?

Yes.  Use:

	while True:
	    line in F.readline()
	    if not line:
	        break
	    pos = F.tell()
	    ...

Seriously, the problem here is that iterating over a while has the same
effect as F.xreadlines()  For efficiency, the reads are buffered, so
interacting with the file object while you're using one of these methods
results in weird behavior.  If you want to interact with the file object
while you're also reading in lines, you should not use either of those
mechanisms.

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ Something to remember you by.
\__/  Leonard Shelby




More information about the Python-list mailing list