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
目录2 个章节
代码实现
# 创建一个目录来保存这些东西
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')
参考资料
- 官方文档:https://docs.python.org/zh-cn/3/library/zipfile.html
- 用 Python 压缩文件方法汇总:https://qiwsir.github.io/2021/09/15/compressandarchivefile/
- How to Create and Serve Zipfiles from Django:https://pybit.es/articles/django-zipfiles/
_EOF_
Python创建压缩文件
- 本文作者:
- 程序设计实验室
- 版权声明:
- 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
相关文章
python实现解析markdown文档中的图片,并且保存到本地~
背景 前阵子简书好像说是凉了,搞得我有点小慌,毕竟我的大部分博客都是放在简书上面的,虽然简书提供了打包导出功能,但是只能导出文字,图片的话还是存在简书服务器上面,再加上我一直想要重新做一个个人博客,于是就有了这篇文章。 思路 首先是要解析markdown文档,然后获取到其中的所有图片,再把图片按md文件分好目录保存。 解析markdown文档 这里我用了misaka模块,据说是python的mar
2021-12-18 · Python · 约 1 分钟
Python中的三元表达式
一般语言的三元表达式都是这种形式: result = statement ? true : false // For examle result = a b ? a : b Python中的三元表达式比较特殊,用下面这种形式 result = true if statement else false # For example result = a if a b else b
2022-05-27 · Python · 约 1 分钟
2025年了,在 Django 之外,Python Web 框架还能怎么选?
2025年了,Django之外还剩啥?LiteStar轻量快,Tortoise ORM省心,Granian丢掉Nginx,RobynPython+Rust。独立开发者终于不用被全家桶绑架?
2025-09-14 · Python · 约 1 分钟
关于Python的异常处理
前言 异常处理在任何一门编程语言里都是值得关注的一个话题,良好的异常处理可以让你的程序更加健壮,清晰的错误信息更能帮助你快速修复问题。在Python中,和部分高级语言一样,使用了try/except/finally语句块来处理异常,如果你有其他编程语言的经验,实践起来并不难。 Python 中(至少)有两种错误:语法错误和异常( syntax errors 和 exceptions )。下面稍微介
2022-05-27 · Python · 约 1 分钟
讨论
共 0 条加载评论中…