DA
DealiAxy
2022年09月30日

Python创建压缩文件

代码实现 # 创建一个目录来保存这些东西 temp_path = os.path.join(settings.MEDIA_ROOT, 'temp', str(uuid.uuid4())) os.makedirs(temp_path) # 创建压缩文件 archive_path = os.path.join(temp_path, 'archive.zip') with zipfile.ZipFile

未分类
824
3 分钟阅读
更新于 09-30

代码实现

# 创建一个目录来保存这些东西
temp_path = os.path.join(settings.MEDIA_ROOT, 'temp', str(uuid.uuid4()))
os.makedirs(temp_path)
# 创建压缩文件
archive_path = os.path.join(temp_path, 'archive.zip')
with zipfile.ZipFile(archive_path, 'w') as zf:
    # 把图片添加到压缩文件中
    zf.write(image_path, arcname=f'{photo.pk}.png')
    zf.write(image_path, arcname=f'{photo.pk}.png')
    zf.write(image_path, arcname=f'{photo.pk}.png')
    zf.write(image_path, arcname=f'{photo.pk}.png')

# 返回压缩文件地址,下载
return HttpResponseRedirect(f'{settings.MEDIA_URL}temp/{os.path.basename(temp_path)}/archive.zip')

参考资料