Skip to content
Advertisement

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

Advertisement

Answer

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 the basename, you avoid the need to move to a common folder at all.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement