这是我的:
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/