Monday, April 21, 2025

Compress Multiple Files to Individual ZIP Files in One Go

import zipfile, os

os.chdir('c:\\Python38-64\\include')

for x in os.listdir():
    if x.endswith('.h'):
        handle = zipfile.ZipFile(x + '.zip', 'w')
        handle.write(x, compress_type = zipfile.ZIP_DEFLATED)
        handle.close()

This Python code uses the zipfile and os modules to compress all the header files (.h) in the c:\Python38-64\include directory and its subdirectories into individual ZIP files.

The os module is used to change the current working directory to c:\Python38-64\include using the os.chdir() method. Then, the os.listdir() method is used to get a list of all files and directories in the current directory.

The if statement is used to filter out only the files that end with .h. For each header file, a new ZIP file is created with the same filename as the header file but with a .zip extension using the zipfile.ZipFile() method. The compress_type argument is set to zipfile.ZIP_DEFLATED to use the ZIP file compression method.

The header file is added to the ZIP file using the write() method of the ZIP file handle. Finally, the ZIP file is closed using the close() method of the ZIP file handle.

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 .  ...