如何在Python中使用bzip2压缩文件? [英] How to compress a file with bzip2 in Python?

查看:67
本文介绍了如何在Python中使用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的好例子.

And I know about BZ2File but, I cannot find any good example to use BZ2File.

推荐答案

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

The documentation for bz2.compress for says it takes data, not a file name.
Try replacing the line below:

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

...或者:

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

这篇关于如何在Python中使用bzip2压缩文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆