Bartłomiej 'furas' Burek
furas.pl
# prywatne notatki - Python, Linux, Machine Learning, etc.

Python: How to change name when compressing to Zip file or uncompressing from Zip file.

2020.03.03 - wtorek / kategoria: Python / tagi: python /

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()
Książki: python-dla-kazdego-podstawy-programowania python-wprowadzenie python-leksykon-kieszonkowy python-receptury python-programuj-szybko-i-wydajnie python-projekty-do-wykorzystania black-hat-python-jezyk-python-dla-hackerow-i-pentesterow efektywny-python-59-sposobow-na-lepszy-kod tdd-w-praktyce-niezawodny-kod-w-jezyku-python aplikacje-internetowe-z-django-najlepsze-receptury