More Refinements

A Byte of Python 

Go to the Table of Contents. Visit the Gifcom web site.

The fourth version is a satisfactorily working script for most users, but there is always room for improvement. For example, you can include a verbosity level for the program where you can specify a -v option to make your program become more talkative.

Another possible enhancement would be to allow extra files and directories to be passed to the script at the command line. We will get these from the sys.argv list and we can add them to our source list using the extend method provided by the list class.

One refinement I prefer is the use of the tar command instead of the zip command. One advantage is that when you use the tar command along with gzip, the backup is much faster and the backup created is also much smaller. If I need to use this archive in Windows, then WinZip handles such .tar.gz files easily as well. The tar command is available by default on most Linux/Unix systems. Windows users can download and install it as well.

The command string will now be:

tar = 'tar -cvzf %s %s -X /home/swaroop/excludes.txt' % (target, ' '.join(srcdir))

The options are explained below.

  • -c indicates creation of an archive.

  • -v indicates verbose i.e. the command should be more talkative.

  • -z indicates the gzip filter should be used.

  • -f indicates force in creation of archive i.e. it should replace if there is a file by the same name already.

  • -X indicates a file which contains a list of filenames which must be excluded from the backup. For example, you can specify *~ in this file to not include any filenames ending with ~ in the backup.


The most preferred way of creating such kind of archives would be using the zipfile or tarfile module respectively. They are part of the Python Standard Library and available for you to use already. Using these libraries also avoids the use of the os.system which is generally not advisable to use because it is very easy to make costly mistakes using it.

However, I have been using the os.system way of creating a backup purely for pedagogical purposes, so that the example is simple enough to be understood by everybody but real enough to be useful.