Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 943
gaba Avatar asked Jul 16 '15 13:07

gaba


People also ask

How do I create an empty zip file in Python?

empty_zip_data is the data of an empty zip file. For Python 3 use empty_zip_data = b'PK\x05... .

How do I create a new zip file?

Right-click on the file or folder.Select “Compressed (zipped) folder”. To place multiple files into a zip folder, select all of the files while hitting the Ctrl button. Then, right-click on one of the files, move your cursor over the “Send to” option and select “Compressed (zipped) folder”.

How do I create a zip file in Pycharm?

Go inside your Pycharm project directory -> select all -> Right Click -> send to compressed (zip). This may result in the inclusion of some unneeded directories (__pycache__, . idea), but would not affect the program execution. If needed, you may skip those two directories while creating the zip.


2 Answers

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

like image 147
gaba Avatar answered Sep 23 '22 05:09

gaba


I use shutil to zip like so:

import shutil
shutil.make_archive(archive_name, '.zip', folder_name)
like image 23
Seraphim Avatar answered Sep 21 '22 05:09

Seraphim