search

Home  >  Q&A  >  body text

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:我知道这是异常……

PHPzPHPz2812 days ago1551

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:26:31

    SAD, I finally solved it myself...
    The next source code of the file io set the flag bit

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

    tell will detect the flag

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

    seek will clear the flag (there are too many code distributions so I won’t post it)
    Look for the source code yourself for details...

    reply
    0
  • Cancelreply