How to extract a zip file in Python
In this tutorial, we are going to see different ways to unzip or extract one or more files from a zip file in a given directory.
Python’s zipfile module provides the ZipFile class which provides a member function called ZipFile.extractall() to extract all the content of a ZIP file.
Extracting all the files of a zip in the current directory
To work on zip files using python, we will use a built-in python module called “zipfile” which has the “extractall()” method to extract all files and folders from a zip file into the current directory. Here is the code you can use to extract files:
from zipfile import ZipFile # specifying the name of the zip file file = "archive.zip" # open the zip file in read mode with ZipFile(file, 'r') as zip: # list all the contents of the zip file zip.printdir() # extract all files print('extraction...') zip.extractall() print('Done!')
The above program extracts the zip file named “archive.zip” in the same directory of this script.
Extract all the files of a zip into another directory
We can also pass a directory name to extractall() function to extract all files and folders to a specific directory. If the folder you passed as a parameter does not exist, this method will create one for you. Here is the code you can use to extract files:
from zipfile import ZipFile # specifying the name of the zip file file = "archive.zip" # open the zip file in read mode with ZipFile(file, 'r') as zip: # extract all files to another directory zip.extractall('zip_destination')
The above code will extract all the files contained in “archive.zip” into the “zip_destination” folder.
Extract a single zip file
This is similar to extracting multiple files but this time you must first provide the filename and path. In addition, you must use the extract() method instead of extractall(). Here is a basic code snippet for extracting a single file.
import zipfile zip = zipfile.ZipFile('C:\\User\\dir\\archive.zip') zip.extract('logo.jpg', 'C:\\User\\dir') zip.close()