在 Python 中读取大文件的惰性方法?

新手上路,请多包涵

我有一个 4GB 的大文件,当我尝试读取它时,我的计算机挂起了。所以我想一块一块地阅读它,在处理每一块之后将处理过的块存储到另一个文件中并读取下一块。

有什么方法可以 yield 这些片段吗?

我很想有一个 懒惰的方法

原文由 Pratik Deoghare 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 377
2 个回答

要编写惰性函数,只需使用 yield

 def read_in_chunks(file_object, chunk_size=1024):
    """Lazy function (generator) to read a file piece by piece.
    Default chunk size: 1k."""
    while True:
        data = file_object.read(chunk_size)
        if not data:
            break
        yield data

with open('really_big_file.dat') as f:
    for piece in read_in_chunks(f):
        process_data(piece)


另一种选择是使用 iter 和辅助函数:

 f = open('really_big_file.dat')
def read1k():
    return f.read(1024)

for piece in iter(read1k, ''):
    process_data(piece)


如果文件是基于行的,则文件对象已经是行的惰性生成器:

 for line in open('really_big_file.dat'):
    process_data(line)

原文由 nosklo 发布,翻译遵循 CC BY-SA 4.0 许可协议

file.readlines() 接受一个可选的大小参数,它近似于返回行中读取的行数。

 bigfile = open('bigfilename','r')
tmp_lines = bigfile.readlines(BUF_SIZE)
while tmp_lines:
    process([line for line in tmp_lines])
    tmp_lines = bigfile.readlines(BUF_SIZE)

原文由 Anshul 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题