gab*_*aba 9 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
Run Code Online (Sandbox Code Playgroud)
我是从这里得到的.
但我改为s = StringIO.StringIO()
,s = io.BytesIO()
因为我使用的是Python 3.x.
zip文件确实创建了正确的大小等.但我无法打开它.它无效.如果我将zip文件写入磁盘,则zip文件有效.
我使用 Shutil 来压缩,如下所示:
import shutil
shutil.make_archive(archive_name, '.zip', folder_name)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1164 次 |
最近记录: |