Sometimes, we want to unzip files with Python.
In this article, we’ll look at how to unzip files with Python.
How to unzip files with Python?
To unzip files with Python, we can use the zipfile
module.
For instance, we write:
import zipfile
path_to_zip_file = 'test.zip'
directory_to_extract_to = './test'
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
zip_ref.extractall(directory_to_extract_to)
We read the zip file into a Python object with zipfile.ZipFile(path_to_zip_file, 'r')
.
Then we call extractall
on the returned zip file object to do the extraction.
We specify the directory_to_extract_to
to extract the zip file’s contents.
Now we should see the test
folder having the content of the zip file after the code is run.
Conclusion
To unzip files with Python, we can use the zipfile
module.