How to compress a file with bzip2 in Python?

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-08 15:25:18

问题


Here is what I have:

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()

I know first param of bz2.compress is a data, but it's the simple way that I found to clarify what I need.

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


回答1:


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)

...or maybe :

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


来源:https://stackoverflow.com/questions/39604843/how-to-compress-a-file-with-bzip2-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!