[英]How to compress a file with bzip2 in Python?
這是我有的:
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的好例子。
bz2.compress的文檔說它需要數據,而不是文件名。
請嘗試替換以下行:
tarbz2contents = bz2.compress(open(source_file, 'rb').read(), compressionLevel)
...或者可能 :
with open(source_file, 'rb') as data:
tarbz2contents = bz2.compress(data.read(), compressionLevel)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.