How to unzip files using Python?
We need to use the zipfile module to extract the files using Python. Check the Python zipFile module-related documents on its official site: https://docs.python.org/3/library/zipfile.html#module-zipfile
ZIP file object class
We need to use zipfile object class in order to extract the files. To extract the files and folders it supports two methods, extract and extractall.
The below example we are going to use is for the Windows OS.
- extractall() method.
This method is used when extracting all the files from a specific zip to the destination folder.
The syntax of this method is,
ZipFile.extractall(path=None, members=None, pwd=None)
Here, zipfile is the class name and the extractall is the method.
Example,
from zipfile import ZipFile
with ZipFile("C:\\Temp\\TestFolder.zip",'r') as zFile :
zFile.extractall("C:\Temp\\ExtractedFolder")
In the above example, we call ZipFile class from the zipfile module and then read the zip file to extract the zip file to the specific folder (here ExtractedFolder).
- extract() method
This method is used when you need to extract a single from the zip.
The syntax of this method is,
ZipFile.extract(member, path=None, pwd=None)
Example,
from zipfile import ZipFile
with ZipFile("C:\\Temp\\TestFolder.zip",'r') as zFile :
zFile.extract("Test.txt","C:\\Temp\\ExtractedFolder")
In the above example, Test.txt will be extracted to the C:\Temp\ExtractedFolder path.
Once, you are done with the zip file operation, it is always recommended to close the zipfile using the close() method so it will be available to other processes.
In the above example, in the last line you can write,
zFile.close()