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

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts