Search code examples
pythonfilezippython-2.5

How do I zip the contents of a folder using python (version 2.5)?


Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents.

Is this possible?

And how could I go about doing it?


Solution

  • Adapted version of the script is:

    #!/usr/bin/env python
    from __future__ import with_statement
    from contextlib import closing
    from zipfile import ZipFile, ZIP_DEFLATED
    import os
    
    def zipdir(basedir, archivename):
        assert os.path.isdir(basedir)
        with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z:
            for root, dirs, files in os.walk(basedir):
                #NOTE: ignore empty directories
                for fn in files:
                    absfn = os.path.join(root, fn)
                    zfn = absfn[len(basedir)+len(os.sep):] #XXX: relative path
                    z.write(absfn, zfn)
    
    if __name__ == '__main__':
        import sys
        basedir = sys.argv[1]
        archivename = sys.argv[2]
        zipdir(basedir, archivename)
    

    Example:

    C:\zipdir> python -mzipdir c:\tmp\test test.zip
    

    It creates 'C:\zipdir\test.zip' archive with the contents of the 'c:\tmp\test' directory.