Python3 交互模式 next(文件) 之后 文件.tell() OSError 恢复的问题?

交互模式输入:

f = open( "Config.h", "r+", encoding="UTF-8" )
next(f)
f.tell()

这样会报错:

OSError: telling position disabled by next() call

原因可以理解
但是之后再在交互模式里输入 f.tell() 会报一样的错误
想来是 disabled by next() 还没被恢复
但是 f.seek 重设置一下之后 f.tell 就不会报错了
想问下具体细节是怎样的?
disabled by next() 如何被恢复的?
PS:呃,忘了说,是 Python3……
PS:我知道这是异常……

阅读 6.7k
2 个回答

SAD,最后还是我自己解决的……
文件 io 的 next 源码设置了标志位

def __next__(self):
    self._telling = False
    line = self.readline()
    if not line:
        self._snapshot = None
        self._telling = self._seekable
        raise StopIteration
    return line

tell 里会检测标志位

if not self._telling:
    raise OSError("telling position disabled by next() call")

seek 会清除标志位(代码分布太多不贴了)
详细自己去找源码看……

所以,根据https://stackoverflow.com/que...,要避免这个问题的话:
1)改用f.readline(), 就可以用f.tell()了
2)或者把tell()换成offset += len(line)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题