【问题标题】:How to compress a file with bzip2 in Python?如何在 Python 中使用 bzip2 压缩文件?
【发布时间】:2016-09-20 22:43:29
【问题描述】:

这是我所拥有的:

import bz2

compressionLevel = 9
source_file = '/foo/bar.txt' #this file can be in a different format, like .csv or others...
destination_file = '/foo/bar.bz2'

tarbz2contents = bz2.compress(source_file, compressionLevel)
fh = open(destination_file, "wb")
fh.write(tarbz2contents)
fh.close()

我知道 bz2.compress 的第一个参数是一个数据,但这是我发现的用来阐明我需要什么的简单方法。

我知道 BZ2File,但是我找不到任何使用 BZ2File 的好例子。

【问题讨论】:

    标签: python compression bzip2


    【解决方案1】:

    documentation for bz2.compress 表示它需要数据,而不是文件名。
    尝试替换下面的行:

    tarbz2contents = bz2.compress(open(source_file, 'rb').read(), compressionLevel)
    

    ...或者也许:

    with open(source_file, 'rb') as data:
        tarbz2contents = bz2.compress(data.read(), compressionLevel)
    

    【讨论】:

    • 伟大的@Gerrat!第一个选项对我有用。谢谢!
    • 我不认为第二个选项是完全正确的。我觉得应该是with open(source_file, 'rb') as data: tarbz2contents = bz2.compress(data.read(), compressionLevel)
    猜你喜欢
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    • 2012-12-12
    • 1970-01-01
    • 2019-10-19
    • 2011-01-20
    相关资源
    最近更新 更多