In this tutorial, I will be sharing 5 really useful tips when working with zip archive file using the zipfile library in Python.

If you have never use zipfile module before, zipfile is a standard Python module specifically dealing with zip files to create, read, write, append, and list a ZIP file.


Buy Me a Coffee? Your support is much appreciated!
PayPal Me: https://www.paypal.me/jiejenn/5
Venmo: @Jie-Jenn





Source Code:

import os
import zipfile

# 1: List all the files and folders
fileName = 'CoffeeShop Vintage Honey.zip'
zFile = zipfile.ZipFile(os.path.join(os.getcwd(), fileName), 'r')
zip_name_list = zFile.namelist()
print(zip_name_list)


# 2: check if file is a zip file and must exist on your PC
print(zipfile.is_zipfile('test.zip'))


# 3: extract files
zFile.extractall(os.path.join(os.getcwd(), 'Unzipped'))


zFile.extract('CoffeeShop Vintage Honey/CoffeeShop Vintage Honey ad.jpg',
              os.path.join(os.getcwd(), 'Unzipped'))


# 4: Access the metadata
zip_file_info = zFile.getinfo(
    'CoffeeShop Vintage Honey/CoffeeShop Vintage Honey ad.jpg')

print(zip_file_info.file_size)
print(zip_file_info.compress_size)
print(zip_file_info.is_dir())
print(zip_file_info.orig_filename)

print(zFile.printdir())


# 5: Create a zipfile
myZipFile = zipfile.ZipFile('Test2.zip', 'w')
myZipFile.write('corgi.jpg', 'Image\\corgi2.jpg')
myZipFile.write('myprint.png', 'Image\\myprint.png')
myZipFile.write('test.py', 'Python Script/test.py')
myZipFile.close()