Monday, April 21, 2025

File Size Before and After ZIP Compression - Python

import zipfile

target = 'OLD-BACKUP.zip'

handle = zipfile.ZipFile(target)

listing = handle.namelist()

for x in listing:
    res = handle.getinfo(x)
    print('-' * 79)
    print('Filename: ', res.filename)
    print('Before: ', res.file_size)
    print('After: ', res.compress_size)

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.

The code then loops through the listing variable and for each item in the list:

  1. It gets information about the item in the ZIP archive using the getinfo() method of the ZipFile object handle and stores the information in a variable named res.
  2. It then prints a separator of 79 dashes to visually separate the output for each item in the archive.
  3. It prints the filename of the item in the archive, obtained from the filename attribute of the ZipInfo object res.
  4. It prints the size of the file before compression, obtained from the file_size attribute of the ZipInfo object res.
  5. It prints the size of the file after compression, obtained from the compress_size attribute of the ZipInfo object res.

So, this code essentially displays the filenames, original sizes, and compressed sizes 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 .  ...