Unzipping files in Python
Here is a code snippet that demonstrates how to unzip a file using the zipfile module in Python:
Here is a code snippet that demonstrates how to unzip a file using the zipfile module in Python:
Unzip a file using the zipfile module in Python
import zipfile
# specify the zip file path
file_path = "path/to/zip/file.zip"
# create a ZipFile object
with zipfile.ZipFile(file_path, 'r') as zip_ref:
# extract all the contents
zip_ref.extractall("path/to/extract/to")This code creates a ZipFile object by passing the path of the zip file to the zipfile.ZipFile() function. The 'r' argument tells the function to open the file in read mode. Then the extractall() method is used to extract all the contents of the zip file to the specified directory.
You can also extract a single file by calling the extract() method and passing it the filename:
Extract a single file by calling the extract() method and passing it the filename
with zipfile.ZipFile(file_path, 'r') as zip_ref:
zip_ref.extract("filename.txt")The zipfile module also supports password-protected zip files. You can set the password on the ZipFile instance after opening it:
Extract a password-protected file
with zipfile.ZipFile(file_path, 'r') as zip_ref:
zip_ref.setpassword(b"password")
zip_ref.extractall("path/to/extract/to")Note: Python's built-in
zipfilemodule only supports basic ZipCrypto encryption, not AES. When extracting untrusted archives, be aware of zip-slip vulnerabilities. In Python 3.12+, you can mitigate this by passingfilter='data'toextractall().