How to Use zipfile Module in Python: Syntax and Examples
Use the
zipfile module in Python to create, read, and extract ZIP files by opening a ZIP archive with zipfile.ZipFile(). You can add files with .write(), extract files with .extractall(), and list contents with .namelist().Syntax
The zipfile.ZipFile class is used to work with ZIP files. You open a ZIP file by specifying the file name and mode:
'r'- read an existing ZIP file'w'- write a new ZIP file (overwrites if exists)'a'- append to an existing ZIP file
Common methods include:
.write(filename)- add a file to the ZIP.extractall(path)- extract all files to a folder.namelist()- list all files inside the ZIP
python
import zipfile # Open a ZIP file for writing with zipfile.ZipFile('example.zip', 'w') as zipf: zipf.write('file1.txt') # Add file1.txt to the ZIP # Open a ZIP file for reading with zipfile.ZipFile('example.zip', 'r') as zipf: print(zipf.namelist()) # List files inside the ZIP zipf.extractall('extracted') # Extract all files to 'extracted' folder
Output
['file1.txt']
Example
This example creates a ZIP file named archive.zip, adds two text files to it, lists the contents, and then extracts all files to a folder named output.
python
import zipfile # Create a ZIP file and add files with zipfile.ZipFile('archive.zip', 'w') as zipf: zipf.write('file1.txt') zipf.write('file2.txt') # Read the ZIP file with zipfile.ZipFile('archive.zip', 'r') as zipf: print('Files in ZIP:', zipf.namelist()) zipf.extractall('output')
Output
Files in ZIP: ['file1.txt', 'file2.txt']
Common Pitfalls
Common mistakes when using zipfile include:
- Forgetting to open the ZIP file in the correct mode (
'w'to write,'r'to read). - Trying to add files that do not exist, which causes errors.
- Not closing the ZIP file properly (use
withstatement to avoid this). - Extracting files without specifying a safe path can overwrite important files.
python
import zipfile # Wrong: opening ZIP in read mode but trying to write try: with zipfile.ZipFile('test.zip', 'r') as zipf: zipf.write('file.txt') # This will raise an error except Exception as e: print('Error:', e) # Right: open ZIP in write mode to add files with zipfile.ZipFile('test.zip', 'w') as zipf: zipf.write('file.txt')
Output
Error: ZIP file is not writable
Quick Reference
| Method | Description |
|---|---|
| zipfile.ZipFile(filename, mode) | Open a ZIP file with mode 'r', 'w', or 'a' |
| .write(filename) | Add a file to the ZIP archive |
| .extractall(path) | Extract all files to the specified folder |
| .namelist() | Return a list of file names in the ZIP |
| .close() | Close the ZIP file (use 'with' to avoid manual close) |
Key Takeaways
Use zipfile.ZipFile with the correct mode to read, write, or append ZIP files.
Always use the 'with' statement to ensure the ZIP file closes properly.
Use .write() to add files and .extractall() to extract files safely.
Check .namelist() to see what files are inside a ZIP archive.
Avoid errors by ensuring files exist before adding and opening ZIP in the right mode.