Leandro
Leandro

Reputation: 950

compress multiple files into a bz2 file in python

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?

Upvotes: 1

Views: 2944

Answers (4)

fantabolous
fantabolous

Reputation: 22706

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)

Upvotes: 0

THAVASI.T
THAVASI.T

Reputation: 181

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

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155363

This is what tarballs are for. The tar format packs the files together, then you compress the result. 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. 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('mytar', 'bztar', directory_to_compress)

Upvotes: 1

Vincent Rodomista
Vincent Rodomista

Reputation: 780

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

Upvotes: 0

Related Questions