如何在Python中进行交互式压缩,跟踪目录中每个文件的完成情况?

问题描述 投票:0回答:1

我正在编写一个Python脚本,将目录中的多个文件夹压缩到新目录中的单个文件中,如本文中所述:在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)

但是,我想增强该过程的交互性并显示哪些文件已完成压缩。实现此功能的最佳方法是什么?

脚本每次完成时应显示此消息

/location/file.zip/

python python-3.x zip interactive
1个回答
0
投票

检查

zipped_filepath
函数中
create_zip
的值,将该行插入代码中。这将在执行期间显示压缩文件路径。

print(f'Zipped: {zipped_filepath}') # Added print statement
© www.soinside.com 2019 - 2024. All rights reserved.