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 许可协议。转载请注明出处!
相关文章
Jupyter-Notebook-简单配置
安装主题 默认主题太丑了,必须换个好看的主题,pip安装: pip install jupyterthemes 装完之后: # 列出所有主题 jt -l # 设置主题 # -T 启用工具栏 # -N 启用名称栏 jt -t 主题名称 -T -N 自动补全 安装nbextensions pip install jupyter_contrib_nbextensions jupyter contrib
2021-12-18 · Python · 约 1 分钟
现代 Python 程序优雅处理日期时间的避坑指南
Python 时间处理还是得踩坑?`datetime`、`time`、`calendar` 搞得人头大,Naive vs Aware 时区陷阱更是坑爹。2026 年了还用 `pytz`?标准库 `ZoneInfo` 加上 `Pendulum`、`Arrow` 才叫现代化,至少不用再写反人类的时间字符串解析。数据库存 UTC,前端传 ISO 8601,简单点行不行?
2026-03-25 · Python · 约 1 分钟
Python踩坑:类与类对象类型参数传递与使用
前言 对初学者来说,Python确实简单好用,毕竟动态类型语言,不用定义就可以拿来用,类型之间随意转换简直不要太方便,因此Python用来写写小脚本,爬虫程序什么的,没什么问题。 不过,一旦用来开发稍微大型一点的项目,例如搭建一个Web应用,就会遇到一些问题,一般缺乏经验的人都会陷入某些坑中。= =... 坑 先说坑,函数参数类型是一坑,类与类的对象这又是一坑。 虽然之前用其他静态类型语言(例如C
2022-05-27 · 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 分钟
讨论
共 0 条加载评论中…