【问题标题】:Python create zip filePython 创建 zip 文件
【发布时间】:2015-10-06 00:01:16
【问题描述】:

我使用以下脚本创建 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 文件是有效的。

【问题讨论】:

  • @MalikBrahimi 对不起。我不明白你的问题
  • @MalikBrahimi:gaba 正在尝试将 zip 数据写入s
  • 很奇怪。我刚刚测试了代码的 zip 部分(在 Python 2.6.6 上),将 s.getvalue() 作为二进制文件写入磁盘,它对我来说很好。
  • 刚刚开始工作(看看我的回答)。谢谢大家:)

标签: python django python-3.x


【解决方案1】:

我使用shutil来压缩:

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

【讨论】:

    【解决方案2】:

    我让它工作了。只需将resp['Content-length'] = size 中的大小更改为s.tell()

    【讨论】:

    • 现在说得通了。是的,“内容长度”需要是您发送的实际数据的大小,而不是压缩前的大小。
    • @PM2Ring 是的。谢谢你的解释。
    • 对不起,但对我来说它不起作用。 zip 文件有内容,但我无法解压缩
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    相关资源
    最近更新 更多