
本文介绍如何使用 Python 的 zipfile 模块实现交互式的目录压缩,并在压缩过程中跟踪每个文件的完成情况。通过修改现有的压缩脚本,在压缩完成后打印出已压缩文件的路径,从而提供更友好的用户体验。本文将提供详细的代码示例和步骤,帮助开发者轻松实现这一功能。
现有的 Python 脚本可以方便地将目录下的多个文件夹压缩成独立的 ZIP 文件。为了增强用户体验,我们需要在压缩过程中显示已完成压缩的文件路径。这可以通过在 create_zip 函数中添加一个简单的 print 语句来实现。
以下是修改后的 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)在上述代码中,我们在 create_zip 函数的 zip_obj.close() 之后添加了 print(f'Zipped: {zipped_filepath}') 语句。这将在每个 ZIP 文件创建完成后,立即打印出该文件的完整路径。
立即学习“Python免费学习笔记(深入)”;
为了测试这段代码,你需要创建两个目录:to_zip(INPUT_FOLDER)和 zipped(OUTPUT_FOLDER)。在 to_zip 目录下,创建几个子目录,每个子目录中包含一些文件。运行脚本后,你将在控制台中看到每个 ZIP 文件的压缩进度。
例如,如果 to_zip 目录下包含名为 folder1 和 folder2 的两个子目录,运行脚本后,你将看到如下输出:
Zipped: zipped/folder1.zip Zipped: zipped/folder2.zip
通过在 create_zip 函数中添加一个简单的 print 语句,我们可以轻松地实现交互式的目录压缩,并向用户提供有关压缩进度的反馈。这种方法简单有效,可以显著提升用户体验。对于更复杂的进度跟踪需求,可能需要更高级的技术,例如使用 tqdm 库创建进度条。
以上就是Python 实现交互式压缩:跟踪每个文件的压缩进度的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号