AppDividend
Latest Code Tutorials

Python Unzip File: How To Extract Single or Multiple Files

Python ZipFile is a class of zipfile module for reading and writing zip files. ZIP is the archive file format that supports lossless data compression.

By lossless compression, we mean that the compression algorithm allows the original data to be entirely reconstructed from the compressed data.

A ZIP file is a single file containing one or more compressed files, offering an easy way to make large files smaller and keep related files together.

Python unzip file

To work on zip files using Python, we will use an inbuilt python module called zipfile. In Python’s zipfile module, the ZipFile class provides a member function to extract all the ZIP archive contents.

To unzip a file in Python, use the ZipFile.extractall() method. The extractall() method takes a path, members, pwd as an argument, and extracts all the contents.

Syntax

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

It accepts the following parameters :

  1. path: location where zip file needs to be extracted; if not provided, it will extract the contents in the current directory.
  2. members: list of files to be extracted. It will extract all the files in the zip if this argument is not provided.
  3. pwd: If the zip file is encrypted, then pass the password in this argument default is None.

Example of Python unzip

Let’s say, in my current working directory, I have a zip file called Mail3.zip, and I want to unzip it using ZipFile.extractall() method.

See the following code.

# app.py

from zipfile import ZipFile

with ZipFile('Mail3.zip', 'r') as zipObj:
   # Extract all the contents of zip file in current directory
   zipObj.extractall()

Output

python3 app.py

It will extract the files in the same Directory as your programming app.py file.

It will extract all the files in the zip at the current Directory.  If files with the same name are already present at the extraction location, it will overwrite those files.

We have used Python with statement to open the files. “Python with” ensures that open file descriptors are closed automatically after program execution leaves the context of the with statement. 

Extract all files from a zip file to different Directory

We can extract all the files from the zip file to a different directory, and to do that, we need to pass the destination location as an argument in extractall(). The path can be relative or absolute.

See the following code.

1 Comment
  1. Fradrick Munyurwa says

    I don’t have .zip files, but ones ending with ,el; ,en; ,es; ,kl; ,no; ,ta; ,ko; and ,zh-CN; all downloaded after running PIP on a Coursera course. How do I decompress these ones?

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.