How to Extract Zip File in Python: Simple Guide
To extract a zip file in Python, use the
zipfile module. Open the zip file with ZipFile and call extractall() to unpack all contents.Syntax
The basic syntax to extract a zip file is:
zipfile.ZipFile('filename.zip', 'r'): Opens the zip file in read mode.extractall(path): Extracts all files to the specified directory. Ifpathis omitted, extracts to the current directory.close(): Closes the zip file after extraction.
python
import zipfile with zipfile.ZipFile('example.zip', 'r') as zip_ref: zip_ref.extractall('destination_folder')
Example
This example shows how to extract all files from sample.zip into a folder named extracted_files. It uses a context manager to handle the file safely.
python
import zipfile zip_path = 'sample.zip' extract_to = 'extracted_files' with zipfile.ZipFile(zip_path, 'r') as zip_ref: zip_ref.extractall(extract_to) print(f"Extracted all files to '{extract_to}'")
Output
Extracted all files to 'extracted_files'
Common Pitfalls
Common mistakes when extracting zip files include:
- Not using
withor forgetting to close the zip file, which can lock the file. - Extracting to a directory without write permission, causing errors.
- Assuming the zip file exists without checking, which raises
FileNotFoundError. - Extracting files without validating paths, which can lead to security risks if zip contains absolute or relative paths.
python
import zipfile # Wrong way: Not closing the file zip_ref = zipfile.ZipFile('sample.zip', 'r') zip_ref.extractall('extracted') # zip_ref.close() is missing # Right way: Using context manager with zipfile.ZipFile('sample.zip', 'r') as zip_ref: zip_ref.extractall('extracted')
Quick Reference
| Method | Description |
|---|---|
| ZipFile('file.zip', 'r') | Open zip file in read mode |
| extractall(path=None) | Extract all files to given path or current directory |
| extract(member, path=None) | Extract a single file from the archive |
| namelist() | List all file names in the archive |
| close() | Close the zip file |
Key Takeaways
Use the zipfile module's ZipFile class to open and extract zip files.
Always use a context manager (with statement) to ensure the zip file closes properly.
extractall() extracts all files; specify a path to control where files go.
Check that the zip file exists and you have write permission to the extraction folder.
Be cautious of zip files with unsafe paths to avoid security issues.