Working with Zip via Python

Reading ZIP Files via Python


import zipfile, os

os.chdir('D:\\') # move to the folder with example.zip

exampleZip = zipfile.ZipFile('example.zip')

print(exampleZip.namelist()) # Output: ['example-folder/', 'example-folder/example-file2.txt', 'example-file.txt']

fileInfo = exampleZip.getinfo('example-file.txt')

print(fileInfo.file_size) # Output: 72

print(fileInfo.compress_size) # Output: 22

print('Zip file is %sx smaller!' % (round(fileInfo.file_size / fileInfo.compress_size, 2))) # Output: 'Zip file is 3.0x smaller!'

exampleZip.close()

Extracting from ZIP Files via Python


import zipfile, os

os.chdir('D:\\') # move to the folder with example.zip

exampleZip = zipfile.ZipFile('example.zip')

exampleZip.extractall()

exampleZip.close()

Creating and Adding to ZIP Files via Python


import zipfile, os

os.chdir('D:\\') # move to the folder with example.zip

newZip = zipfile.ZipFile('example.zip', 'a') # 'a' - append, 'w' - write (override)

newZip.write('example-file3.txt', compress_type=zipfile.ZIP_DEFLATED)

newZip.close()

Leave a Comment