I need to compress multiple files into one bz2 file in python. I'm trying to find a way but I can't can find an answer. Is it possible?
compress multiple files into a bz2 file in python
2.6k Views Asked by Leandro At
4
There are 4 best solutions below
2
On
Take a look at python's bz2 library. Make sure to google and read the docs first!
https://docs.python.org/2/library/bz2.html#bz2.BZ2Compressor
0
On
you have import package for:
import tarfile,bz2
and multilfile compress in bz format
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
an use
os.path.basename(src_file)
open a only for file
0
On
Python's standard lib zipfile handles multiple files and has supported bz2 compression since 2001.
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)
This is what tarballs are for. The
tarformat packs the files together, then you compress the result. Python makes it easy to do both at once with thetarfilemodule, where passing a "mode" of'w:bz2'opens a new tar file for write with seamlessbz2compression. Super-simple example:If you don't need much control over the operation,
shutil.make_archivemight be a possible alternative, which would simplify the code for compressing a whole directory tree to: