How to List Files in a Zip Archive in Python
Use Python's
zipfile module to open a zip file and call namelist() on the ZipFile object to get a list of all files inside. This method returns a list of file names as strings.Syntax
To list files in a zip archive, first import the zipfile module. Then open the zip file using zipfile.ZipFile('filename.zip'). Use the namelist() method on the ZipFile object to get a list of all file names inside the archive.
zipfile.ZipFile(file, mode='r'): Opens the zip file in read mode.namelist(): Returns a list of all file names in the zip archive.
python
import zipfile with zipfile.ZipFile('example.zip', 'r') as zip_ref: file_names = zip_ref.namelist()
Example
This example shows how to open a zip file named example.zip and print all the file names inside it.
python
import zipfile with zipfile.ZipFile('example.zip', 'r') as zip_ref: files = zip_ref.namelist() for file in files: print(file)
Output
document.txt
images/photo.png
notes/todo.txt
Common Pitfalls
Some common mistakes when listing files in a zip archive include:
- Not opening the zip file in read mode (
'r'), which is required to list files. - Forgetting to use a context manager (
withstatement), which can leave the file open. - Assuming
namelist()returns file objects instead of file names (it returns strings).
python
import zipfile # Wrong: opening in write mode will not allow listing # with zipfile.ZipFile('example.zip', 'w') as zip_ref: # print(zip_ref.namelist()) # Right way: with zipfile.ZipFile('example.zip', 'r') as zip_ref: print(zip_ref.namelist())
Quick Reference
| Method | Description |
|---|---|
| zipfile.ZipFile(file, mode='r') | Open a zip file for reading |
| namelist() | Return a list of all file names in the zip archive |
| in operator | Check if a file name exists in the archive |
| extract(file) | Extract a specific file from the archive |
Key Takeaways
Use zipfile.ZipFile with mode 'r' to open zip files for reading.
Call namelist() on the ZipFile object to get all file names inside the archive.
Always use a with statement to safely open and close the zip file.
namelist() returns a list of strings representing file paths inside the zip.
Avoid opening the zip file in write mode when only listing files.