Zippping a directory recursively from Python script on Windows

Mike C. Fletcher mcfletch at rogers.com
Wed Mar 10 14:00:54 CET 2004


Max M wrote:
...

> Can it really be that there is no free .zip command line tool for 
> Windows, or are my Googling skills just to poor?

I believe InfoZip is a free command-line zip/unzip utility, but I may be 
wrong about that, I normally use cygwin tar & gzip.

> Or is there a more Pythonic approach?

Honestly, I wouldn't do this myself, I just tell everyone to get tar and 
gzip, but here's a simple example of using ZipFile for creating zips of 
directories.  You'd want to check for .jpg, .mpg, etceteras and avoid 
compressing those most likely, but the basics are there.

HTH,
Mike

import zipfile, os

def toZip( directory, zipFile ):
    """Sample for storing directory to a ZipFile"""
    z = zipfile.ZipFile(
        zipFile, 'w', compression=zipfile.ZIP_DEFLATED
    )
    def walker( zip, directory, files, root=directory ):
        for file in files:
            file = os.path.join( directory, file )
            # yes, the +1 is hacky...
            archiveName = file[len(os.path.commonprefix( (root, file) ))+1:]
            zip.write( file, archiveName, zipfile.ZIP_DEFLATED )
            print file
    os.path.walk( directory, walker, z  )
    z.close()
    return zipFile


if __name__ == "__main__":
    toZip( 'v:\\temp', 'c:\\temp\\test.zip' )

_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/






More information about the Python-list mailing list