| Store | Cart

Zippping a directory recursively from Python script on Windows

From: Mike C. Fletcher <mcfl...@rogers.com>
Wed, 10 Mar 2004 08:00:54 -0500
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/

Recent Messages in this Thread
Max M Mar 10, 2004 11:51 am
Gerrit Muller Mar 10, 2004 11:55 am
Piet van Oostrum Mar 10, 2004 12:52 pm
Max M Mar 10, 2004 12:56 pm
Mike C. Fletcher Mar 10, 2004 01:00 pm
Max M Mar 10, 2004 01:22 pm
Larry Bates Mar 11, 2004 02:46 pm
Max M Mar 11, 2004 08:54 am
Messages in this thread