How to Write and append to zip archives in Python

Writing and appending to zip archives dynamically using Python is our need to manage the space on server. In my previous article you have seen how to read zip archives in Python. Now we are concentrating on How to Write and append to existing zip archives using Python.

We will take the same zip files for our example on reading zip files, I suggest you go back and give it a quick look. The two files we will be using are: “file1.txt” and “file2.txt”.

If you just want a new zip file with your files in it, then it’s a matter of a few lines using the zipfile module. First, create the archive in write mode:

Then start adding files:

That’s essentially it. The zipfile module handles all the details of opening and reading the files, compressing them and inserting them into the archive. Don’t believe me? Then let’s take a look. First we close the file, then reopen it in read mode.

The printdir() method of a zipfile works just like the function we wrote in the last article to print out the files in the archive. You can also check that the files contain the data we expect:

But what if we want to add files to an existing zip? It’s simple enough, we just need to open the file in append mode. Opening an existing zip file in write mode will erase the zip, so be careful when you’re using that mode.

Let’s say theres a “file3.txt” with the following contents:

We add it to the zip we just made ( with the following code:

Finally, you can write a program to extract zip files to disk in just a few lines. The following Python program extracts all zip files given as arguments to the current directory.

In action, it looks like this:

Be careful, this simple program will only work if the zip archive has a flat file structure, i.e. it contains no nested directories. If it does, you’ll need to adjust the program to create the directories as it goes, but I’ll leave that extension up to you.

Leave me a comment and let me hear your opinion. If you’ve got any thoughts, comments or suggestions for things we could add, leave a comment! Also please Subscribe to our RSS for latest tips, tricks and examples on cutting edge stuff.

0 I like it
0 I don't like it