Python创建zip文件

时间:2015-07-16 13:41:59

标签: python django python-3.x

我使用以下脚本创建ZIP文件:

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

我是从here得到的。

但我将s = StringIO.StringIO()更改为s = io.BytesIO(),因为我使用的是Python 3.x。

zip文件确实以正确的大小等创建。但我无法打开它。它无效。如果我将zip文件写入磁盘,则zip文件有效。

2 个答案:

答案 0 :(得分:3)

我得到了它的工作。只需将resp['Content-length'] = size的尺寸更改为s.tell()

即可

答案 1 :(得分:1)

我像这样使用shutil拉链:

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