有时候我们去读取超大的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)
网友评论