Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rename files written to zip file using Zipfile module python

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading