Listing Files in a Zip File Using Python

Python can be used for seeing what’s inside a Zip File without even unzipping it. In this article, I’ll discuss How to list all of file names inside a zip file using Python?

Steps for Listing File Names in Zip File

  1. Import zipfile module
  2. Read in a zip file as a File Object using zipfile.ZipFile(filepath, “r”)
  3. Call namelist() function on File Object, which returns list of names of files in Zip File
  4. Iterate over list of file names and print out name of each file
  5. Close File Object using file.close()

Python Code for Listing File Names in a Zip File

# Import zipfile module
import zipfile

# Read in zipfile
file = zipfile.ZipFile("file.zip", "r")

# Iterate over list of file names of files in zipfile
for name in file.namelist():
	print(name)

Output of Above Code

file3.txt
__MACOSX/._file3.txt
file4.txt
__MACOSX/._file4.txt
file5.txt
__MACOSX/._file5.txt
file2.txt
__MACOSX/._file2.txt
file1.txt
__MACOSX/._file1.txt

Meaning that file.zip have five files file5.txt, file3.txt, file4.txt, file2.txt, file1.txt

Comments to: Listing Files in a Zip File Using Python

Your email address will not be published.