本文介绍了python中tqdm模块用于显示程序运行进度条以及zipfile模块用于压缩文件。

有些程序运行过程是比较漫长的,所以最好能够有一个简单的进度条工具能够告诉我们处理了多少,然后还需要多少时间。这里以压缩文件为例,介绍「tqdm」模块的使用。

import os
from datetime import date
import zipfile
import time
from tqdm import tqdm

# 指定要压缩的源目录路径
source_dir = './2024-06-18'

# 获取当前日期作为输出文件名前缀
current_date = date.today().strftime("%Y-%m-%d")

# 构造输出文件名(以 .zip 结尾)
output_file_name = f"{current_date}_archive.zip"

total_size = sum(os.path.getsize(os.path.join(root, file)) for root, _, files in os.walk(source_dir) for file in files)
try:
    with zipfile.ZipFile(output_file_name, 'w') as zip_file:
        with tqdm(total=total_size/(1024*1024), unit='MB', desc='压缩进度', unit_scale=True) as pbar:
            start_time = time.time()
            for root, dirs, files in os.walk(source_dir):
                for file in files:
                    file_path = os.path.join(root, file)
                    rel_path = os.path.relpath(file_path, source_dir)
                    file_size = os.path.getsize(file_path)
                    zip_file.write(file_path, rel_path)
                    
                    pbar.update(file_size/(1024*1024))
                    elapsed_time = time.time() - start_time
                    try:
                        estimated_time_remaining = (total_size - pbar.n * (1024 * 1024)) / (pbar.n * (1024 * 1024) / elapsed_time)
                    except:
                        estimated_time_remaining = 0
                    if total_size > 0:
                        speed_mb_s = round(pbar.n / elapsed_time, 2)
                        pbar.set_postfix({
                            '剩余时间': f"{int(estimated_time_remaining // 60)}分{int(estimated_time_remaining % 60)}秒",
                        })
                    
    print(f'压缩成功。输出文件为 {output_file_name}')
except Exception as e:
    print(f'执行压缩失败,错误信息:{e}')

使用 tqdm 可以对 pbar 设置的几个参数包括:

  • total:表示总任务大小,既可以是文件个数,也可以是文件总大小
  • unit:任务大小的单位,我这里选择了文件大小,因为要根据这个来估计剩余时间
  • desc:进度条前面的描述字符串
  • unit_scale:如果显示文件大小,进度条显示浮点数会非常长,所以开启unit_scale,变得美观一点

估算剩余时间是取用了 pbar 在迭代过程中的 n 值,然后再综合总文件大小和已经处理的速度来做的线性估计。这个可以根据不同算法的时间复杂度进行调整。但是对于 zip 文件压缩而言已经足够了。

额外计算的剩余时间的内容,可以在 pbar.set_postfix 方法中以字典的方式打印出来。

最后修改:2024 年 09 月 18 日
请大力赞赏以支持本站持续运行!