在 python 中使用 gzip 压缩大文件

Compresing large files with gzip in python

我在python搜索了如何压缩文件,找到的答案基本如下所述:

with open(input_file, 'rb') as f_in, gzip.open(output_file, 'wb') as f_out:
    f_out.write(f_in.read())

它可以轻松处理 1GB 的文件。但我计划将文件压缩到 200 GB。

有什么我需要考虑的因素吗?对于这样的大文件,我应该采用不同的方式吗?

这些文件是二进制 .img 文件(块设备的导出;通常末尾为空 space,因此压缩效果很好)。

这会将整个文件读入内存,如果您没有 200G 可用空间,就会给您带来麻烦!

您可以简单地通过 gzip 传输文件,避免 Python 它将分块处理工作

% gzip -c myfile.img > myfile.img.gz

否则你应该分块读取文件(选择大块大小可能会提供一些好处)

BLOCK_SIZE = 8192

with open(myfile, "rb") as f_in, gzip.open(output_file, 'wb') as f_out:
    while True:
        content = f_in.read(BLOCK_SIZE)
        if not content:
            break
        f_out.write(content)