Welcome, guest | Sign In | My Account | Store | Cart

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.

Python, 11 lines
 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

5 comments

Ravi Teja Bhupatiraju 19 years, 8 months ago  # | flag

Some Corrections!

import tarfile, os

destination = 'F:/test.tar.bz2'
fileorfoldertobackup = './pgaccess'

out = tarfile.TarFile.open(destination, 'w:bz2')
out.add(fileorfoldertobackup, arcname=os.path.basename(fileorfoldertobackup))
out.close()



Ravi Teja Bhupatiraju.
<pre>

</pre>

Ravi Teja Bhupatiraju 19 years, 8 months ago  # | flag

???

Not sure how my comment ended up here. I posted it for
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/299412
Ed Gordon (author) 19 years, 8 months ago  # | flag

Changes Made. I made some changes to the recipe to reflect your suggestions- most notably that I left out the import statements. Doh!

Ravi Teja Bhupatiraju 19 years, 8 months ago  # | flag

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?

Vivek Vaidyanathan 15 years, 8 months ago  # | flag

hmm... addfile does not work for a whole directory.

Created by Ed Gordon on Thu, 12 Aug 2004 (PSF)
Python recipes (4591)
Ed Gordon's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks