tags:

views:

1172

answers:

3

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? A point in the right direction (i.e. a link with an example) or an example that I can see would be extremely helpful. Thanks in advance.

+4  A: 

Use zipfile module:

import zipfile

compressedFile = zipfile.ZipFile(FILENAME,"a", zipfile.ZIP_DEFLATED)
compressedFile.write(existing_file_name, archived_name)
kgiannakakis
+4  A: 

Here is a recursive version

def zipfolder(path, relname, archive):
    paths = os.listdir(path)
    for p in paths:
        p1 = os.path.join(path, p) 
        p2 = os.path.join(relname, p)
        if os.path.isdir(p1): 
            zipfolder(p1, p2, archive)
        else:
            archive.write(p1, p2) 

def create_zip(path, relname, archname):
    archive = zipfile.ZipFile(archname, "w", zipfile.ZIP_DEFLATED)
    if os.path.isdir(path):
        zipfolder(path, relname, archive)
    else:
        archive.write(path, relname)
    archive.close()
Kozyarchuk
+5  A: 

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 = os.path.basename(basedir) + ".zip" # archive in the curdir
    zipdir(basedir, archivename)

Example:

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

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

J.F. Sebastian
Man, that's scary... I was just about to post the EXACT code! (apart from contectlib.closing). Even most of the identifiers match! :b
efotinis