gpt4 book ai didi

python - 用python压缩大文件

转载 作者:太空狗 更新时间:2023-10-29 17:43:34 25 4
gpt4 key购买 nike

我想用 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()

我想知道这个语法是否正确,是否有优化它的方法?我觉得我在这里遗漏了一些东西。

非常感谢。

最佳答案

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

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)

关于python - 用python压缩大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9518705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com