Python zipfile module is used to read and write the zip files. Here we will see how to create a zip file in python using zipfile module.

How to create Zip file in python:

Usecase: Choose a directory and make the zip file out of it.

prepare_zip.py
import zipfile
import os

def prepare_zip(dir_path):
    new_file = dir_path + '.zip'
    # creating zip file with write mode
    zip = zipfile.ZipFile(new_file, 'w', zipfile.ZIP_DEFLATED)
    # Walk through the files in a directory
    for dir_path, dir_names, files in os.walk(dir_path):
        f_path = dir_path.replace(dir_path, '')
        f_path = f_path and f_path + os.sep
        # Writing each file into the zip
        for file in files:
            zip.write(os.path.join(dir_path, file), f_path + file)
    zip.close()
    print("File Created successfully..")
    return new_file

if __name__ == '__main__':
    prepare_zip('C:\\Users\\Lenovo\\Documents\\Data')

ZipFile() creates a new zip file with write permissions by taking the path parameter. Walkthrough each file and folders into the given directory and write them into the zip file.

Output:

File Created successfully..

You can see the created zip in the given directory.

How to unzip/extract Zip file in python:

The same data.zip file I am going to extract here. zipfile.extractall() function extracts all members from the archive to the current working directory.

Unzip the file in current working directory:

unzip.py
def extract_zip(dir_path):
    with zipfile.ZipFile(dir_path+'data.zip', 'r') as zip_inst:
        zip_inst.extractall()

The above code extracts the content of the data.zip file in current working directory.

Unzip the file in a different location:

If you wish to extract the content in a different location, you have to supply that path to the extractall(path) function.

unzip.py
def extract_zip(dir_path):
    with zipfile.ZipFile(dir_path+'data.zip', 'r') as zip_inst:
        zip_inst.extractall(dir_path)

Then you can see the extracted content in the given path.

References:

Happy Learning 🙂

About the Author:

Avatar
Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment