python - 如何在 Python 中使用 bzip2 压缩文件?

标签 python compression bzip2

这是我的:

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 的好例子。

最佳答案

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

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

...或者也许:

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

关于python - 如何在 Python 中使用 bzip2 压缩文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39604843/

相关文章:

python - 在 python 中计算到你下一个生日的天数

java - C++和Java之间如何压缩和解压?

hadoop - 多个gz文件转到一个hadoop节点

php - 如何在 PHP 7 中启用 bzip2 支持

python - 在 Windows 上为 python 安装开箱即用的 opencv

python - 让 django-paypal 与 pycrypto 一起工作?

python - 如何使用 xampp 在 ubuntu 中运行 python cgi 脚本

python - Python 源文件的压缩

c# - SevenZipSharp - 如何使用 C# 将多个目录压缩到一个文件中?

javascript - 如何在 javascript/jquery 中解压缩 bzip2 数据?