I was working on a backup utility to compress files and folders into a .tar.bz2 file and found the documentation and internet info to be a bit lacking. So here is an example for those that tackle this in the future.
I initially thought, "Hey, there is a 'tarfile' module and a bz2 module, so I am good to go." Not that easy. The bz2 module does not accept tarfile objects for compression. I hunted around the documentation a and found that bzipping is part of an 'open' class method for a tarfile. But once you make a tarfile.TarFile object, it is too late. Instead, you have to create the tarfile object with 'tarfile.TarFile.open(destination, 'w:bz2'. So here is an example.
1 2 3 4 5 6 7 8 9 10 11
import os import tarfile dstfolder = '/somepath/to/output' fileorfoldertobackup = '/home/username' dst = '%s.tar.bz2' % os.path.join(dstfolder, os.path.basename(fileorfoldertobackup)) out = tarfile.TarFile.open(dst, 'w:bz2') out.addfile(fileorfoldertobackup, arcname=os.path.basename(fileorfoldertobackup)) out.close() You can add as many 'addfile' commands as you would like. I hope this saves someone the momentary confusion I experienced.
The original posting of this recipe was at http://www.edgordon.com/read?article=081204