Skip to content

Python zipfile extract | Unzipping files

  • by

Use extractall() method to extract the zipfile in Python. This method Unzips all the files present in the zip file to the current working directory.

ZipFile.extractall(path=None, members=None, pwd=None)
  • path: location where zip file needs to be extracted, default is current directory.
  • members: list of files to be extracted. Default extract all the files.
  • pwd: If the zip file is encrypted then the pass password in this argument default is None.

Python zipfile extract

A simple example code extracts all files from a zipfile.

from zipfile import ZipFile

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

Output:

Python zipfile extract

Import the zipfile module Create a zip file object using ZipFile class. Call the extractall() method on the zip file object and pass the path where the files needed to be extracted and Extract the specific file present in the zip.

from zipfile import ZipFile
  
# loading the temp.zip and creating a zip object
with ZipFile("C:\\Users\\rohit\\\
Desktop\\temp\\temp.zip", 'r') as zObject:
  
    # Extracting all the members of the zip 
    # into a specific location.
    zObject.extractall(
        path="C:\\Users\\rohit\\Desktop\\temp")

Extracting the specific file present in the zip

from zipfile import ZipFile
  
# loading the temp.zip and creating a zip object
with ZipFile("C:\\Users\\rohit\\Desktop\\temp\\temp.zip", 'r') as zObject:
  
    # Extracting specific file in specific location.
    zObject.extract("text1.txt", path="C:\\Users\\rohit\\Desktop\\temp")
zObject.close()

Do comment if you have any doubts or suggestions on this Python zipfile topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading