【发布时间】: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