简体   繁体   中英

How to temporarily re-name a file or Create a re-named temp-file in Python before zipping it

In the below code I am trying to zip a list list of files, I am trying to rename the files before zipping it. So the file name will be in a more readable format for the user.

It works for the first time, but when I do it again It fails with the error the file name already exists

Returning the response via Django Rest Framework via FileResponse. Is there any more simplistic way to achieve this?

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 has a second parameter, arcname , which allows you to rename files without any copying. You don't need to move file to a separate folder, or actually rename it.

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)

By stripping off thebasename , you avoid the need to move to a common folder at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM