Mad*_*ist 5 python file python-3.x tell
我试图f.tell()在迭代期间在普通文本文件中使用:
with open('test.txt') as f:
for line in f:
print(f.tell())
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
OSError: telling position disabled by next() call
Run Code Online (Sandbox Code Playgroud)
为了确保这一点,我检查了如果我尝试手动跳过一行并丢弃迭代器对象(可能是文件本身),是否会发生相同的错误:
with open('test.txt') as f:
next(f)
print(f.tell())
Run Code Online (Sandbox Code Playgroud)
我的最终目标是找到文件中第一行的长度(以字节为单位),无论平台如何,因此以下工作正常:
with open('test.txt') as f:
f.readline()
print(f.tell())
Run Code Online (Sandbox Code Playgroud)
我很好奇为什么tell在迭代过程中禁用了 using 。我可以理解为什么seek会被禁用,因为大多数迭代器不喜欢并发修改,但为什么呢tell?是否tell执行一些影响迭代器或类似操作的状态更改?
我可能应该提到我正在 Anaconda 环境中运行 Python 3.6.2。我在 Arch Linux 和 Red Hat 7.5 上都观察到了这种行为。
更新
这个问题似乎以不同的形式出现在 Python 2.7 中:file.tell() inconsistency。我想知道缓冲优化引起的不一致是否是tellPython 3中完全禁用的原因。
这实际上提出了一个更深层次的问题,这就是为什么tell当 Python 文件接口的目标是从中抽象出来时,为什么会返回操作系统级文件指针呢?这并不像Python级别指针的位置是模糊或神秘的,有或没有缓冲。
| 归档时间: |
|
| 查看次数: |
855 次 |
| 最近记录: |