ActiveState Code

Recipe 299412: Bzipped Tar Files


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
 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.

Discussion

The original posting of this recipe was at http://www.edgordon.com/read?article=081204

Comments

  1. 1. At 3:50 a.m. on 16 aug 2004, Ravi Teja Bhupatiraju said:

    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>

  2. 2. At 3:53 a.m. on 16 aug 2004, Ravi Teja Bhupatiraju said:

    ???

    Not sure how my comment ended up here. I posted it for
    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/299412
    
  3. 3. At 6:27 a.m. on 16 aug 2004, Ed Gordon (the author) said:

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

  4. 4. At 6:52 a.m. on 17 aug 2004, Ravi Teja Bhupatiraju said:

    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?

  5. 5. At 3:49 a.m. on 19 aug 2008, vivek iyyer said:

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

Sign in to comment