Zipping files/zipfile module

Brian Beck exogen at gmail.com
Tue Aug 1 23:43:44 EDT 2006


OriginalBrownster wrote:
> I want to zip all the files within a directory called "temp"
> and have the zip archive saved in a directory with temp called ziptemp
> 
> I was trying to read up on how to use the zipfile module python
> provides, but I cannot seem to find adequate documentation on function
> itself.
> 
> Perhaps someone could help me in this task?

Hello,

This isn't completely tested, but perhaps it will help you get started:

from os import listdir, mkdir
from os.path import join, basename, isfile
from zipfile import ZipFile

def zip_dir(path, output_path, include_hidden=True):
    files = [join(path, f) for f in listdir(path) if isfile(join(path, f))]
    try:
        mkdir(output_path)
    except OSError, e:
        if e.errno == 17: # Path exists
            pass
    zip_file = ZipFile(join(output_path, 'temp.zip'), 'w')
    for f in files:
        if basename(f).startswith('.') and not include_hidden:
            continue
        print "Adding %s to archive..." % (f,)
        zip_file.write(f)
    zip_file.close()

Use like:
    zip_dir('temp', 'temp/ziptemp')

Note that if you want to add the entire contents of a directory
(subdirectories, recursively), you should consider using os.walk or
something similar. This will only add the file contents of the directory.
I'm not sure if the zipfile module provides any nice ways to write
directories to the archive, but I'm assuming it just involves writing an
arcname with a '/' in it (see help(zipfile.ZipFile)).

-- 
Brian Beck
Adventurer of the First Order



More information about the Python-list mailing list