#written on 10/2/2007 by Red Byer #embedded as part of ioah2ical, but works solo just fine. # # Use for examples, whatever, but no warranty expressed or implied. # # # PURPOSE: zip up a directory. Why is this not included as part of python's # zipfile module?? import os import os.path import zipfile import zlib from datetime import datetime def zipDir(givenpath): '''Recursively zips everything below a directory, attempting to keep directory structure in place. Utilizes os.walk, so you will need PYthon 2.4 or later. Windows uses weird path delimiters and this function not verified to work with windoze''' path = givenpath.rstrip() #remove any trailing whitespace if not os.path.isdir(path): raise IOError, 'File given instead of directory. Try again.' readmepath = os.path.join(path, "ZipCreationDate.txt") readmefile = open(readmepath, 'w') readmestring = "This zip file created on " + datetime.now().isoformat(' ') readmefile.write(readmestring) readmefile.close() print '' print "Zipping up %s" % path np = path.rstrip('\\/') #remove possible trailing slashes #this is needed for naming our zip easier myzipname = np + ".zip" #create zip at same level as our directory myzip = zipfile.ZipFile(myzipname, 'w', zipfile.ZIP_DEFLATED) try: #currently not catching exceptions in any meaningful way for root, dirs, files in os.walk(path): ziproot = root.replace(path, '') #limited the directory nesting inside our zip print "ZIPROOT ==== ", ziproot for name in files: if not (name == ".DS_Store"): # Macintrash.... get rid of it absfilepath = os.path.join(root, name) filepathinzip = os.path.join(ziproot,name) print "Zipping file ", filepathinzip myzip.write(absfilepath, filepathinzip) finally: #we really should do this no matter what. print "Closing ", myzipname myzip.close() os.remove(readmepath) return None