简体   繁体   English

在python中将多个文件压缩成一个bz2文件

[英]compress multiple files into a bz2 file in python

I need to compress multiple files into one bz2 file in python.我需要将多个文件压缩成 python 中的一个 bz2 文件。 I'm trying to find a way but I can't can find an answer.我试图找到一种方法,但我找不到答案。 Is it possible?可能吗?

This is what tarballs are for. 这就是tarball的用途。 The tar format packs the files together, then you compress the result. tar格式将文件打包在一起,然后压缩结果。 Python makes it easy to do both at once with the tarfile module , where passing a "mode" of 'w:bz2' opens a new tar file for write with seamless bz2 compression. 使用tarfile模块 ,Python可以轻松地一次完成这两项操作,在其中传递'w:bz2'的“模式”将打开一个新的tar文件,以进行无缝bz2压缩进行写入。 Super-simple example: 超简单的例子:

import tarfile

with tarfile.open('mytar.tar.bz2', 'w:bz2') as tar:
    for file in mylistoffiles:
        tar.add(file)

If you don't need much control over the operation, shutil.make_archive might be a possible alternative, which would simplify the code for compressing a whole directory tree to: 如果您不需要对该操作进行太多控制,可以使用shutil.make_archive作为替代方案,它将简化用于压缩整个目录树的代码以:

shutil.make_archive('mytar', 'bztar', directory_to_compress)

Take a look at python's bz2 library. 看一下python的bz2库。 Make sure to google and read the docs first! 请确保先搜索并阅读文档!

https://docs.python.org/2/library/bz2.html#bz2.BZ2Compressor https://docs.python.org/2/library/bz2.html#bz2.BZ2Compressor

you have import package for: 您具有以下目的的导入包:

import tarfile,bz2

and multilfile compress in bz format 和multilfile压缩为bz格式

tar = tarfile.open("save the directory.tar.bz", "w:bz2")
for f in ["gti.png","gti.txt","file.taz"]:
    tar.add(os.path.basename(f))
tar.close()

let use for in zip format was open in a directory open file 让我们使用zip格式在目录打开文件中打开

an use 使用

os.path.basename(src_file)

open a only for file 打开一个仅用于文件

Python's standard lib zipfile handles multiple files and has supported bz2 compression since 2001. Python 的标准 lib zipfile可以处理多个文件,并且从 2001 年开始就支持 bz2 压缩。

import zipfile
sourcefiles = ['a.txt', 'b.txt']
with zipfile.ZipFile('out.zip', 'w') as outputfile:
   for sourcefile in sourcefiles:
      outputfile.write(sourcefile, compress_type=zipfile.ZIP_BZIP2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM