Finding position in file during iteration

杀马特。学长 韩版系。学妹 提交于 2019-12-10 16:24:47

问题


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.

来源:https://stackoverflow.com/questions/48055409/finding-position-in-file-during-iteration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!