Python unzip: How to Extract Single or Multiple Files

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

Syntax

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

Parameters

It accepts the following parameters :

  1. path: location where the 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 removed. If this argument is not provided, it will extract all the files in the zip.
  3. pwd: If the zip file is encrypted, pass the password in this argument default is None.

Example of unzip() function

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

from zipfile import ZipFile

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

If you run the above code, it will extract the files in your programming app.py file in the same directory.

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, they will overwrite.

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

Extracting all files from a zip file to a different directory

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

from zipfile import ZipFile

with ZipFile('Mail3.zip', 'r') as zipObj:
  # Extract all the contents of zip file in different directory
  zipObj.extractall('temp')
  print('File is unzipped in temp folder') 

1 thought on “Python unzip: How to Extract Single or Multiple Files”

  1. 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?

    Reply

Leave a Comment

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