Python: How to change name when compressing to Zip file or uncompressing from Zip file.
Compressing with new name
Sometimes we want to change name of compressed file or put it in subfolder in zip file.
Function zipfile.write()
can get new name which will be used inside zip file
write("folder_on_disk/name_on_disk", "folder_in_zip_file/name_in_zip_file")
Example
import zipfile
import os
z = zipfile.ZipFile('output.zip', 'w')
z.write('images/image.gif', 'new_folder/new_name.gif')
z.close()
# test
z = zipfile.ZipFile('output.zip')
print(z.namelist())
Uncompressing with new name
Sometimes we want to change name of uncompressed file or put it in subfolder od disk.
Function zipfile.extract()
can't change it but we can use zipfile.read()
with standard open()
, write()
Example
import zipfile
import os
z = zipfile.ZipFile('output.zip')
#os.makedirs('other_folder', exist_ok=True)
f = open('other_folder/other_image.gif', 'wb'):
f.write(z.read('new_folder/new_name.gif'))
f.close()
If you like it
Buy a Coffee
Buy a Coffee