Home > Back-end >  Rename files written to zip file using Zipfile module python
Rename files written to zip file using Zipfile module python

Time:01-03

How can I change the file name for files added to the zip file without affecting the original file?

with ZipFile('myZip.zip', 'w') as zipObj2:
     for file in filelist:
         zipObj2.write(file)

I want the file names to be random and not the actual name. So something like

with ZipFile('myZip.zip', 'w') as zipObj2:
     for file in filelist:
         file.rename(os.urandom(10).hex())
         zipObj2.write(file)

CodePudding user response:

The ZipFile.write method takes a second argument, arcname, which is the name of the file inside the archive. So something like:

for file in filelist:
    zipObj2.write(file, os.urandom(10).hex())

would add the file with a random name.

Reference

  • Related