Python Extract ZIP Files: A Step Guide – Python Tutorial

By | November 29, 2021

In this tutorial, we will introduce you how to extract files from a zip file using python. We will use python zipfile class to implement it.

In order to extract files from a zip file, we can do as follows:

Open a zip file

We can use ZipFile.open() function to open a zip file.

ZipFile.open(name, mode='r', pwd=None, *, force_zip64=False)

We should notice: if this zip file contains password, we should set pwd parameter.

Here is an example to open a zip file:

with ZipFile('spam.zip') as myzip:

Extract files from zip file

We can use ZipFile.extract() or ZipFile.extractall() functions to extract files in zip file.

ZipFile.extract(member, path=None, pwd=None)

Here member is the file name you want to extract from a zip file.

or

ZipFile.extractall(path=None, members=None, pwd=None)

If you want to know all members in a zip file, you can read example code below:

import zipfile

file_zip_name = r'F:\github-jupyter\Azure\MachineLearningNotebooks.zip'

try:
    with zipfile.ZipFile(file_zip_name) as f:
        for m in f.namelist():
            print(m)
except Exception as e:
    print(e)

Run this code, you will see:

Python Extract ZIP Files: A Step Guide - Python Tutorial

If you only want to extract a single file from a zip file, you can do as follows:

try:
    with zipfile.ZipFile(file_zip_name) as f:
        f.extract("MachineLearningNotebooks-master/Dockerfiles/1.0.10/")
except Exception as e:
    print(e)

Run this code, you will see:

Python Extract a Single File from a ZIP File

If you want to extract all files in a zip file to a destination folder, you can see this example:

try:
    with zipfile.ZipFile(file_zip_name) as f:
        f.extractall("F:\\")
except Exception as e:
    print(e)

Then you will see this result.

Python Extract All Files from a ZIP File

Leave a Reply