Creating Compressed Files with Python
Code implementation # Create a directory to save these things temp_path = os.path.join(settings.MEDIA_ROOT, 'temp', str(uuid.uuid4())) os.makedirs(temp_path) # Create the compressed file archive_path = os.path.join(temp_path, 'archive.zip') with zipfile.ZipFile
目录2 个章节
Code Implementation
# 创建一个目录来保存这些东西
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')
References
- Official documentation: https://docs.python.org/zh-cn/3/library/zipfile.html
- A summary of methods for compressing files with Python: https://qiwsir.github.io/2021/09/15/compressandarchivefile/
- How to Create and Serve Zipfiles from Django: https://pybit.es/articles/django-zipfiles/
_EOF_
Creating Compressed Files with Python
- 本文作者:
- 程序设计实验室
- 版权声明:
- 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
相关文章
Python踩坑:类与类对象类型参数传递与使用
前言 对初学者来说,Python确实简单好用,毕竟动态类型语言,不用定义就可以拿来用,类型之间随意转换简直不要太方便,因此Python用来写写小脚本,爬虫程序什么的,没什么问题。 不过,一旦用来开发稍微大型一点的项目,例如搭建一个Web应用,就会遇到一些问题,一般缺乏经验的人都会陷入某些坑中。= =... 坑 先说坑,函数参数类型是一坑,类与类的对象这又是一坑。 虽然之前用其他静态类型语言(例如C
2022-05-27 · Python · 约 1 分钟
Python中的双端队列:collections-deque
关于deque 起因是我想做一个「手气不错」的功能,为了提高性能,打算用队列实现,偶然在Stack Overflow看到一个讨论「Efficiency of using a Python list as a queue」 python的list有pop方法,可以实现队列的取出功能,不过据说性能一般般,高赞回答说的 You won't run out of memory using the list
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 分钟
讨论
共 0 条加载评论中…