Finding position in file during iteration

2019-06-25 07:04发布

问题:

I am trying to use f.tell() in a normal text file during iteration:

with open('test.txt') as f:
    for line in f:
        print(f.tell())

I get the following error:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
OSError: telling position disabled by next() call

Just to make sure, I checked that the same error occurs if I try skipping a line manually, discarding the iterator object (which is probably the file itself):

with open('test.txt') as f:
    next(f)
    print(f.tell())

My end goal is to find the length of the first line in a file in bytes, regardless of platform, so the following works just fine:

with open('test.txt') as f:
    f.readline()
    print(f.tell())

I am curious as to why using tell is disabled during iteration. I can understand why seek would be disabled, given that most iterators don't like concurrent modification, but why tell? Does tell perform some state-change that impacts the iterator or something like that perhaps?

I should probably mention that I am running Python 3.6.2 in an Anaconda environment. I have observed this behavior on both Arch Linux and Red Hat 7.5.

Update

This issue seems to appear in Python 2.7 in a different form: file.tell() inconsistency. I wonder if the inconsistency caused by the buffering optimization is the reason tell is disabled completely in Python 3.

This actually brings up a deeper question, which is why does the OS-level file pointer gets returned by tell at all, when the goal of the Python file interface is to abstract away from that? It's not like the position of the Python level pointer is ambiguous or mysterious, with or without buffering.