Friday, October 5, 2012

Archiving Made Easy at Python 2.7

At python 2.7, there is a great shutil tool called make_archive().  It can make either a .zip or .tar file, and eliminates the need to create a walking function to compress files.

The function supports the following compression types by default:
  • zip
  • bztar
  • gztar
  • tar
But if you have another format, you can register it using the register_archive_format().

compressFile = shutil.make_archive(r"c:\temp\mycompressfile", "zip", r"c:\temp\data")
Notice that the first parameter doesn't have the file extension.  The function will return the path to the newly created compressed file.

To uncompress the file, you will have to do that manually using zipfile or tarfile modules.