Based on this answer, is there an option to rename the file when extracting it? Or what is the best solution to do so?
Didn't find anything on the documentation
I found two methods:
Using ZipFile.read()
You can get data from zip file using ZipFile.read()
and write it with new name
using standard open()
, write()
import zipfile
z = zipfile.ZipFile('image.zip')
for f in z.infolist():
data = z.read(f)
with open('new_name.png', 'wb') as fh:
fh.write(data)
Using zipfile.extract() with ZipInfo
You can change name before using extract()
import zipfile
z = zipfile.ZipFile('image.zip')
for f in z.infolist():
#print(f.filename)
#print(f.orig_filename)
f.filename = 'new_name.png'
z.extract(f)
This version can automatically create subfolders if you use
f.filename = 'folder/subfolder/new_name.png'
z.extract(f)
f.filename = 'new_name.png'
z.extract(f, 'folder/subfolder')