Adding folders to a zip file using python

I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder.

So I want to end up with a zip file with a single folder with files in.

I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject.

I started out with this:

def addFolderToZip(myZipFile,folder):
    folder = folder.encode('ascii') #convert path to ascii for ZipFile Method
    for file in glob.glob(folder+"/*"):
            if os.path.isfile(file):
                print file
                myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED)
            elif os.path.isdir(file):
                addFolderToZip(myZipFile,file)

def createZipFile(filename,files,folders):
    curTime=strftime("__%Y_%m_%d", time.localtime())
    filename=filename+curTime;
    print filename
    zipFilename=utils.getFileName("files", filename+".zip")
    myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing 
    for file in files:
        file = file.encode('ascii') #convert path to ascii for ZipFile Method
        if os.path.isfile(file):
            (filepath, filename) = os.path.split(file)
            myZipFile.write( file, filename, zipfile.ZIP_DEFLATED )

    for folder in  folders:   
        addFolderToZip(myZipFile,folder)  
    myZipFile.close()
    return (1,zipFilename)


(success,filename)=createZipFile(planName,files,folders);

Taken from: http://mail.python.org/pipermail/python-list/2006-August/396166.html

Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder.

If I feed the path to a folder in myZipFile.write, I get

IOError: [Errno 13] Permission denied: '..\packed\bin'

Any help is much welcome.

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


Solution 1:

You can also use shutil

import shutil

zip_name = 'path\to\zip_file'
directory_name = 'path\to\directory'

# Create 'path\to\zip_file.zip'
shutil.make_archive(zip_name, 'zip', directory_name)

This will put the whole folder in the zip.

Solution 2:

Ok, after i understood what you want, it is as simple as using the second argument of zipfile.write, where you can use whatever you want:

import zipfile
myZipFile = zipfile.ZipFile("zip.zip", "w" )
myZipFile.write("test.py", "dir\\test.py", zipfile.ZIP_DEFLATED )

creates a zipfile where test.py would be extracted to a directory called dir

EDIT: I once had to create an empty directory in a zip file: it is possible. after the code above just delete the file test.py from the zipfile, the file is gone, but the empty directory stays.