tags:

views:

172

answers:

4

How can I create a zip archive of a directory structure in Python?

+2  A: 

Using the base Python zipfile module.

gab
+3  A: 

You probably want to look at the zipfile module; there's documentation at http://docs.python.org/library/zipfile.html.

You may also want os.walk() to index the directory structure.

me_and
+7  A: 

As others have pointed out, you should use zipfile. The documentation tells you what functions are available, but doesn't really explain how you can use them to zip an entire directory. I think it's easiest to explain with some example code:

#!/usr/bin/env python
import os
import zipfile

def zipdir(path, zip):
    for root, dirs, files in os.walk(path):
        for file in files:
            zip.write(os.path.join(root, file))

if __name__ == '__main__':
    zip = zipfile.ZipFile('Python.zip', 'w')
    zipdir('tmp/', zip)
    zip.close()

Adapted from: http://www.devshed.com/c/a/Python/Python-UnZipped/

Mark Byers
Thank you so much, this is exactly what I was looking for.
Martha Yi
In case you're copy-pasting the code, note that the extension argument actually doesn't do anything.
me_and
Oops, yes I removed the part where it checks the extenions, but forgot to remove the parameter on the function. Thanks for pointing it out.
Mark Byers
Just pointing out, it has been edited but still has the `'.txt'` argument in the function call
Ben James
@Ben James. Fixed it. PS: you have enough rep to edit answers, so you could actually just fix it yourself if you wanted to. :)
Mark Byers
Note that this won't put empty directories into your archive. If that is for some reason desirable, there are workarounds available on the web. (Having to do with manually creating ZipInfo entries for those directories.)
dash-tom-bang
+6  A: 

To add the contents of mydirectory to a new zip file, including all files and subdirectories:

import os
import zipfile

zf = zipfile.ZipFile("myzipfile.zip", "w")
for dirname, subdirs, files in os.walk("mydirectory"):
    zf.write(dirname)
    for filename in files:
        zf.write(os.path.join(dirname, filename))
zf.close()
Ben James
I'd like to upvote that, but I'm wondering if it's not giving the OP a reason to stay lazy (as he obviously didn't open the doc).
e-satis
Actually I found it pretty tricky to work out how to do this from just the docs.
Ben James
Since there is no "recursively add a folder" method, and the required `os.walk` is in another module.
Ben James