登录
首页 >  文章 >  python教程

Python实现实时压缩进度监控

时间:2025-10-30 12:03:34 293浏览 收藏

本篇文章给大家分享《Python 实现实时压缩进度追踪》,覆盖了文章的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

Python 实现交互式压缩:实时追踪文件压缩进度

本文将指导你如何使用 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)

代码解释:

  • 我们在 create_zip 函数中,zip_obj.close() 之后添加了 print(f'Zipped: {zipped_filepath}') 语句。
  • zipped_filepath 变量包含了当前压缩文件的完整路径。
  • print() 函数会将该路径输出到控制台,告知用户该文件已成功压缩。

运行结果

运行修改后的脚本后,每当一个 zip 文件创建完成,控制台会显示类似如下的信息:

Zipped: zipped/folder1.zip
Zipped: zipped/folder2.zip
Zipped: zipped/folder3.zip

这样,用户可以清晰地了解压缩进度,提升用户体验。

注意事项

  • 确保 INPUT_FOLDER 目录下存在需要压缩的子文件夹。
  • 确保 OUTPUT_FOLDER 目录存在,或者脚本有权限创建该目录。
  • 如果需要更详细的进度信息,可以考虑使用第三方库,例如 tqdm,它可以提供更丰富的进度条显示功能。

总结

通过在压缩完成后打印文件路径,我们轻松地实现了交互式压缩,提升了用户体验。这种方法简单有效,适用于各种需要实时反馈的场景。 进一步,可以结合 tqdm 等库,实现更完善的进度展示。

到这里,我们也就讲完了《Python实现实时压缩进度监控》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>