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
Some Corrections!
</pre>
???
Changes Made. I made some changes to the recipe to reflect your suggestions- most notably that I left out the import statements. Doh!
More changes! The main change I was suggesting was the unbound variable dst ( as I remember ) in the previous script.
Another is addfile does not work on my system (XP Home, Python 2.3.2). Didn't check why. add works for me.
A bug in the new script is you have os.path.base.basename. Should be os.path.basename.
One of those days! Huh?
hmm... addfile does not work for a whole directory.