if os.path.exists(scripts_dir_path):
# 打包文件
in_memory_file = io.BytesIO()
with tarfile.open(None, "w:gz", encoding='utf-8', fileobj=in_memory_file, ) as tar:
tar.add(scripts_dir_path, arcname=os.path.basename(scripts_dir_path))
in_memory_file.seek(0)
response = FileResponse(in_memory_file)
# 设置响应头,告诉浏览器以附件形式下载文件
response['Content-Disposition'] = f'attachment; filename="{case_code}.tar.gz"'
return response
# 创建一个内存中的字节流
in_memory_data = io.BytesIO()
with zipfile.ZipFile(in_memory_data, 'w', zipfile.ZIP_DEFLATED) as zipf:
# 递归压缩目录下的所有文件和子目录
for root, dirs, files in os.walk(scripts_dir_path):
for file in files:
file_path = os.path.join(root, file)
# 获取文件file_path相对scripts_dir_path的路径
zip_path = os.path.relpath(file_path, scripts_dir_path)
# 这里写文件数据的时候,拼接上一层目录解压时就有该目录了
zipf.write(file_path, os.path.join(case_code, zip_path))
in_memory_data.seek(0)
response = FileResponse(in_memory_data)
response['Content-Disposition'] = f'attachment; filename="{case_code}.zip"'
return response
使用python压缩一个目录,zip格式和tar.gz格式
最新推荐文章于 2024-07-04 16:04:39 发布