Luc*_*cas 4 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()
Run Code Online (Sandbox Code Playgroud)
我知道bz2.compress的第一个参数是一个数据,但这是我发现来澄清我所需要的简单方法。
我知道BZ2File,但是我找不到使用BZ2File的好例子。
bz2.compress的文档说它需要数据,而不是文件名。
尝试替换下面的行:
tarbz2contents = bz2.compress(open(source_file, 'rb').read(), compressionLevel)
Run Code Online (Sandbox Code Playgroud)
...或许 :
with open(source_file, 'rb') as data:
tarbz2contents = bz2.compress(data.read(), compressionLevel)
Run Code Online (Sandbox Code Playgroud)