
本文将指导你如何使用 Python 实现交互式压缩,并在压缩过程中实时显示已完成压缩的文件路径。通过简单的代码修改,你可以在控制台中看到每个文件压缩完成后的提示信息,从而更清晰地了解压缩进度。
原始代码提供了一个批量压缩目录下子文件夹为独立 zip 文件的功能。为了实现交互式体验,我们需要在每个 zip 文件创建完成后,打印出该文件的路径。 这可以通过在 create_zip 函数中添加一行代码来实现。
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()
print(f'Zipped: {zipped_filepath}') # Added print statement
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)代码解释:
运行修改后的脚本后,每当一个 zip 文件创建完成,控制台会显示类似如下的信息:
立即学习“Python免费学习笔记(深入)”;
Zipped: zipped/folder1.zip Zipped: zipped/folder2.zip Zipped: zipped/folder3.zip
这样,用户可以清晰地了解压缩进度,提升用户体验。
通过在压缩完成后打印文件路径,我们轻松地实现了交互式压缩,提升了用户体验。这种方法简单有效,适用于各种需要实时反馈的场景。 进一步,可以结合 tqdm 等库,实现更完善的进度展示。
以上就是Python 实现交互式压缩:实时追踪文件压缩进度的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号