我需要使用一个索引来记住我在文件中的行数,以便在程序中断时恢复操作。到目前为止,我一直在使用这个:
checkpoint = 15
with open('file.dat', 'rb') as file:
it = iter(file)
for _ in range(checkpoint):
next(it)
try:
while True:
line = next(it)
# do some stuff
checkpoint += 1
except StopIteration:
print("EOF")但这让人感觉笨拙和低效。我一直在想,应用于文件的枚举(或迭代器)是否会维护缓冲读取属性,从而使文件不会一次全部加载到内存中。我现在还为文件中的位置保留了一个行索引。我一直在想这样的事情:
file_offset = 589
with open('file.dat', 'rb') as file:
file.seek(file.offset) # beginning of unprocessed line
for idx, line in enumerate(file):
file_offset = file.tell()
# do stuff这是一种有效的方法,可以在这里正确枚举工作,而不需要将整个工作加载到内存中吗?
发布于 2021-10-11 12:17:54
正如Memory-efficent way to iterate over part of a large file中所指出的,基于所提供的答案,enumerate()创建了一个生成器,以便保持对文件的缓冲读取。
这意味着for i, line in enumerate(file)将产生所需的结果,而无需将整个文件加载到内存中。
https://stackoverflow.com/questions/69525533
复制相似问题