Monday, April 21, 2025

List ALL Files in ZIP Archives Without Decompresion - Python

import zipfile

target = 'OLD-BACKUP.zip'

handle = zipfile.ZipFile(target)

for x in handle.namelist():
    print(x)

This script imports the zipfile module and then opens the file named 'OLD-BACKUP.zip' using the ZipFile() function from the zipfile module.

Once the ZIP file is opened, the code loops through all the files and directories present in the ZIP archive using the namelist() method. For each file and directory, it prints the name to the console using the print() function.

This code essentially lists all the files and directories present in the 'OLD-BACKUP.zip' archive. 

OLD-BACKUP/
OLD-BACKUP/py.ico
OLD-BACKUP/pyc.ico
OLD-BACKUP/pyd.ico
OLD-BACKUP/python_lib.cat
OLD-BACKUP/python_tools.cat
>>> 

The output shows the names of all the files and directories that are present in the root directory of the 'OLD-BACKUP.zip' archive, including:

  • A directory named 'OLD-BACKUP/'.
  • Four .ico files named 'py.ico', 'pyc.ico', 'pyd.ico', and 'python_lib.cat'.
  • A file named 'python_tools.cat'
import zipfile

target = 'OLD-BACKUP.zip'

handle = zipfile.ZipFile(target)

listing = handle.namelist()

file = open('zip-listing.txt', 'w')

for x in listing:
    file.write(x + '\n')

file.close()

This code imports the zipfile module and then opens a ZIP file named 'OLD-BACKUP.zip' using the ZipFile() function from the zipfile module.

The code then uses the namelist() method to get a list of all the files and directories present in the ZIP archive and stores the list in a variable named listing.

Next, the code creates a new file named 'zip-listing.txt' in write mode using the open() function with the 'w' argument. This file will be used to store the listing of all the files and directories present in the ZIP archive.

The code then loops through the listing variable and writes the name of each file and directory to the 'zip-listing.txt' file using the write() method of the file object. The '\n' at the end of each name ensures that each name is written on a new line.

Finally, the code closes the 'zip-listing.txt' file using the close() method of the file object.

This code essentially creates a text file named 'zip-listing.txt' that contains a listing of all the files and directories present in the 'OLD-BACKUP.zip' archive.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...