使用python进行大文件压缩

use*_*959 12 python data-compression

我想用python压缩大文本文件(我说的是> 20Gb文件).我不是一个专家如何,所以我试图收集我发现的信息,以下似乎工作:

import bz2

with open('bigInputfile.txt', 'rb') as input:
    with bz2.BZ2File('bigInputfile.txt.bz2', 'wb', compresslevel = 9) as output:
        while True:
            block = input.read(900000)
                if not block:
                    break
                output.write(block)

input.close()
output.close()
Run Code Online (Sandbox Code Playgroud)

我想知道这种语法是否正确,是否有办法优化它?我的印象是我在这里遗漏了一些东西.

非常感谢.

Fre*_*Foo 18

你的脚本似乎是正确的,但可以缩写:

from shutil import copyfileobj

with open('bigInputfile.txt', 'rb') as input:
    with bz2.BZ2File('bigInputfile.txt.bz2', 'wb', compresslevel=9) as output:
        copyfileobj(input, output)
Run Code Online (Sandbox Code Playgroud)