gaba
gaba

Reputation: 121

Python create zip file

I use the following script to create ZIP files:

import zipfile
import os

def zip_file_generator(filenames, size):

    # filenames = path to the files

    zip_subdir = "SubDirName"
    zip_filename = "SomeName.zip"

    # Open BytesIO to grab in-memory ZIP contents
    s = io.BytesIO()

    # The zip compressor
    zf = zipfile.ZipFile(s, "w")

    for fpath in filenames:
        # Calculate path for file in zip
        fdir, fname = os.path.split(fpath)
        zip_path = os.path.join(zip_subdir, fname)

        # Add file, at correct path
        zf.write(fpath, zip_path)

    # Must close zip for all contents to be written
    zf.close()

    # Grab ZIP file from in-memory, make response with correct MIME-type
    resp = HttpResponse(s.getvalue(), content_type = "application/x-zip-compressed")
    # ..and correct content-disposition
    resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename
    resp['Content-length'] = size

    return resp

I got it from here.

But I changed s = StringIO.StringIO() to s = io.BytesIO() because I am using Python 3.x.

The zip file does get created with the right size etc. But I can't open it. It is invalid. If I write the zip file to disk the zip file is valid.

Upvotes: 9

Views: 1459

Answers (2)

gaba
gaba

Reputation: 121

I got it working. Just change size in resp['Content-length'] = size to s.tell()

Upvotes: 3

Seraphim
Seraphim

Reputation: 181

I use shutil to zip like so:

import shutil
shutil.make_archive(archive_name, '.zip', folder_name)

Upvotes: 1

Related Questions