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:

?View Code PYTHON
1
2
>>> import zipfile
>>> z = zipfile.ZipFile("test2.zip", "w")

Then start adding files:

?View Code PYTHON
1
2
>>> z.write("file1.txt")
>>> z.write("file2.txt")

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.

?View Code PYTHON
1
2
3
4
5
6
>>> z.close()
>>> z = zipfile.ZipFile("test2.zip")
>>> z.printdir()
File Name                                             Modified             Size
file1.txt                                      2008-10-12 14:03:12           54
file2.txt                                      2008-10-12 14:03:32           37

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:

?View Code PYTHON
1
2
3
4
>>> print z.read("file1.txt")
File One Contents
 
"Testing, testing, one two three."

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:

?View Code PYTHON
1
2
3
File Three Contents
 
1234567890

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

?View Code PYTHON
1
2
3
4
5
6
7
8
9
10
11
12
>>> import zipfile
>>> z = zipfile.ZipFile("test2.zip", "a")
>>> z.printdir()
File Name                                             Modified             Size
file1.txt                                      2008-10-12 14:03:12           54
file2.txt                                      2008-10-12 14:03:32           37
>>> z.write("file3.txt")
>>> z.printdir()
File Name                                             Modified             Size
file1.txt                                      2008-10-12 14:03:12           54
file2.txt                                      2007-10-12 14:03:32           37
file3.txt                                      2008-11-12 14:25:46           32

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.

?View Code PYTHON
1
2
3
4
5
6
7
8
9
from zipfile import *
import sys
 
for zipname in sys.argv[1:]:
	z = ZipFile(zipname)
	for filename in z.namelist():
		outfile = file(filename, "w")
		outfile.write(z.read(filename))
		outfile.close()

In action, it looks like this:

?View Code PYTHON
1
2
3
4
5
6
7
8
9
$ ls
test2.zip  unzip.py
$ python unzip.py test2.zip 
$ ls
file1.txt  file2.txt  file3.txt  test2.zip  unzip.py
$ cat file1.txt 
File One Contents
 
"Testing, testing, one two three."

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.

Share:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • DotNetKicks
  • DZone
  • Furl
  • IndianPad
  • Live
  • Netvouz
  • Propeller
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis
  • YahooMyWeb
  • NewsVine
  • Blogosphere News
  • Blogsvine
  • LinkedIn
  • Pownce
  • Upnews
  • BlinkList
  • Global Grind
  • Kirtsy
  • PlugIM
  • ppnow
  • Socialogs
  • Webride
  • Meneame
  • Faves
  • MySpace
  • Yahoo! Buzz
  • Twitter
  • Yahoo! Bookmarks

Related posts

Tagged with: [ ]
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
  • very nice articles thank you...
  • You are welcome evden. I would encourage you to share your experience with us. Let me know if you found any trouble doing the same.
blog comments powered by Disqus