How can I create a zip archive of a directory structure in Python?
+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
2009-12-06 11:17:50
+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
2009-12-06 11:23:55
Thank you so much, this is exactly what I was looking for.
Martha Yi
2009-12-06 11:39:13
In case you're copy-pasting the code, note that the extension argument actually doesn't do anything.
me_and
2009-12-06 11:43:11
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
2009-12-06 12:34:36
Just pointing out, it has been edited but still has the `'.txt'` argument in the function call
Ben James
2009-12-06 20:41:38
@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
2009-12-06 21:22:20
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
2010-04-07 17:16:31
+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
2009-12-06 11:28:24
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
2009-12-06 11:31:26
Actually I found it pretty tricky to work out how to do this from just the docs.
Ben James
2009-12-06 11:34:29
Since there is no "recursively add a folder" method, and the required `os.walk` is in another module.
Ben James
2009-12-06 11:35:07