for line in ftpr: and fptr.tell()

J

Jamey Cribbs

Is it still true that you can't do:

for line in fptr:
pos = fptr.tell()


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?

Thanks!

Jamey Cribbs
 
E

Erik Max Francis

Jamey said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,919
Members
47,460
Latest member
eibafima

Latest Threads

Top