![](/img/trans.png)
[英]Pandas: How do I re-name a multi-level indexed column or create a new column?
[英]How to temporarily re-name a file or Create a re-named temp-file in Python before zipping it
在下面的代码中,我试图 zip 列出文件列表,我试图在压缩之前重命名文件。 因此,文件名将是用户更易读的格式。
它第一次工作,但是当我再次这样做时它失败并出现错误文件名已经存在
通过 Django Rest 框架通过 FileResponse 返回响应。 有没有更简单的方法来实现这一点?
filenames_list=['10_TEST_Comments_12/03/2021','10_TEST_Posts_04/10/2020','10_TEST_Likes_04/09/2020']
with zipfile.ZipFile(fr"reports/downloads/reports.zip", 'w') as zipF:
for file in filenames_list:
friendly_name = get_friendly_name(file)
if friendly_name is not None:
os.rename(file,fr"/reports/downloads/{friendly_name}")
file = friendly_name
zipF.write(fr"reports/downloads/{file}", file, compress_type=zipfile.ZIP_DEFLATED)
zip_file = open(fr"reports/downloads/reports.zip", 'rb')
response = FileResponse(zip_file)
return response
ZipFile.write
有第二个参数arcname
,它允许您重命名文件而无需任何复制。 您无需将file
移动到单独的文件夹,或实际重命名它。
from os.path import basename
for file in filenames_list:
if (name := get_friendly_name(file)) is None:
name = basename(file)
zipF.write(file, name, compress_type=zipfile.ZIP_DEFLATED)
通过剥离basename
,您完全无需移动到一个公共文件夹。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.