美文网首页
OSError: telling position disabl

OSError: telling position disabl

作者: RedB | 来源:发表于2021-01-14 14:26 被阅读0次

有时候我们去读取超大的txt或csv时,因为内存不足,需要逐行读取,并且记忆每次中止时的位置,以便下次使用file.seek(offset)跳过前面读取过的行来继续读取。
如果我们使用如下的代码时:

with open(path, "r+") as f:
    for line in f:
        f.tell() #OSError

就会遇到OSError: telling position disabled by next() call的错误。对此,有两种解决办法。

第一种解决办法 [推荐] :使用 file.readline() 代替 next()

with open(path, mode) as f:
    while True:
        line = f.readline()
        if not line:
            break
        f.tell() #returns the location of the next line

第二种解决办法:使用offset += len(line) 代替 file.tell()

offset = 0
with open(path, mode) as f:
    for line in f:
        offset += len(line)

参考自:https://stackoverflow.com/questions/29618936/how-to-solve-oserror-telling-position-disabled-by-next-call

相关文章

网友评论

      本文标题:OSError: telling position disabl

      本文链接:https://www.haomeiwen.com/subject/xwzmaktx.html