Search code examples
pythonpython-3.xzipinteractive

How to make interactive zipping in Python, tracking completion of each file in a directory?


I am working on a Python script to zip multiple folders within a directory into individual files in a new directory, as discussed in this post: Zip multiple folder (within directory) to individual files (in a new directory), in Python

import os
import zipfile

INPUT_FOLDER = 'to_zip'
OUTPUT_FOLDER = 'zipped'

def create_zip(folder_path, zipped_filepath):
    zip_obj = zipfile.ZipFile(zipped_filepath, 'w')  # create a zip file in the required path
    for filename in next(os.walk(folder_path))[2]: # loop over all the file in this folder
        zip_obj.write(
            os.path.join(folder_path, filename),  # get the full path of the current file
            filename,  # file path in the archive: we put all in the root of the archive
            compress_type=zipfile.ZIP_DEFLATED
        )
    zip_obj.close()

def zip_subfolders(input_folder, output_folder):
    os.makedirs(output_folder, exist_ok=True)  # create output folder if it does not exist
    for folder_name in next(os.walk(input_folder))[1]:  # loop over all the folders in your input folder
        zipped_filepath = os.path.join(output_folder, f'{folder_name}.zip')  # create the path for the output zip file for this folder
        curr_folder_path = os.path.join(input_folder, folder_name)  # get the full path of the current folder
        create_zip(curr_folder_path, zipped_filepath)  # create the zip file and put in the right location

if __name__ == '__main__':
    zip_subfolders(INPUT_FOLDER, OUTPUT_FOLDER)

However, I want to enhance the process to be interactive and display which files have finished zipping. What would be the best approach to achieve this functionality?

The script should show this message /location/file.zip/ per completion.


Solution

  • Check the value of zipped_filepath in the create_zip function, insert the line into the code. This will display the zipped file path during execution.

    print(f'Zipped: {zipped_filepath}') # Added print statement