Python is a great choice for anyone wanting to play with the increasingly popular ZIP or GZIP (not covered here) file formats, and as usual Python makes it surprisingly fun/easy! Don't believe me? In this article we'll look at creating, extracting, and adding to Zip archives using Pythons standard zipfile module and defining a set of functions you can use with your own Zip files; ending with an example which recursively scans a Zip file and sub-archives.
Python is a great choice for anyone wanting to play with the increasingly popular ZIP or GZIP (not covered here) file formats, and as usual Python makes it surprisingly fun/easy!
Don't believe me?
In this article we'll look at creating, extracting, and adding to Zip archives using Pythons standard zipfile module and defining a set of functions you can use with your own Zip files; ending with an example which recursively scans a Zip file and sub-archives.
This does require some prior knowledge of Python, so if you have never used Python before you should read Vikram Vaswani’s Python 101 before reading this.
Creating Our Zip File
Lets jump right in and create our Zip file, then add a few sample files to it.
So we should have small Zip containing two files (file.txt and file.gif) sitting in our current working directory. Easy enough and pretty neat overall. How about something a little more interesting? Adding all the .txt files in a directory to our archive, perhaps?
Still pretty simple. This example basically defines a new user function named zipdir(), which follows three steps..
Loop though a list of all the names in our directory.
If each ends with .txt try and write it to zip.
If an IOError is raised skip this name and move onto the next one (this could happen if you have a folder ending with .txt)
There is a problem with this one though… because ZipFile is a file-based object, data already in our Zip gets wiped when we start writing again just like with normal files. Luckily this also means we can use other flags beside write, to show this we’ll add a few more files to our Zip using append.