该问题是tqdm库的一个bug,目前最新版本的tqdm已经修复了这个问题。可以尝试升级tqdm到最新版本,或者降低到tqdm==4.59.0版本。如果升级或降低版本后仍然存在问题,可以尝试重新安装tqdm库。

以下代码展示了如何使用tqdm库进行文件压缩,并解决'AttributeError: 'tqdm' object has no attribute 'last_print_t''错误:

import os
import subprocess
from tqdm import tqdm


def pack_files(source_dir, output_dir):
    # 检查源目录和输出目录是否存在
    if not os.path.exists(source_dir) or not os.path.isdir(source_dir):
        print(f'源目录{source_dir}不存在或不是一个目录')
        return

    if not os.path.exists(output_dir) or not os.path.isdir(output_dir):
        print(f'输出目录{output_dir}不存在或不是一个目录')
        return

    # 计算文件总数
    total_files = sum([len(files) for root, dirs, files in os.walk(source_dir)])

    # 外层进度条(总进度)
    with tqdm(total=total_files,
              desc='压缩进度',
              bar_format='{desc}:{percentage:3.0f}%|�33[0m�33[32m{bar}�33[0m| [耗时:{elapsed} 速度:{rate_percent:.2f}%/s]',
              dynamic_ncols=True) as pbar:

        for root, dirs, files in os.walk(source_dir):
            for file in files:
                # 获取需要压缩的文件路径
                file_path = os.path.join(root, file)

                # 获取文件名和文件后缀
                file_name, file_ext = os.path.splitext(file)

                # 拼接输出文件路径(去掉文件后缀)
                output_file = os.path.join(output_dir, f'{file_name}.gz')

                if os.path.isdir(file_path):
                    # 处理文件夹,使用tar命令打包并压缩成tar.gz格式
                    tar_file = os.path.join(output_dir, f'{file_name}.tar.gz')
                    subprocess.run(['tar', '-czf', tar_file, file_path])
                    tqdm.write(f'已将文件夹{file_path}打包压缩到{tar_file}')
                else:
                    # 处理文件,使用pigz进行压缩
                    subprocess.run(['pigz', '-c', file_path],
                                   stdout=open(output_file, 'wb'))
                    tqdm.write(f'已将文件{file_path}压缩到{output_file}')

                # 更新外层进度条
                pbar.update(1)


# 路径
source_dir = '/home/115/up'
output_dir = '/home/115/app'
pack_files(source_dir, output_dir)

解决步骤:

  1. 升级tqdm到最新版本:使用 pip install --upgrade tqdm 命令升级到最新版本。
  2. 降低tqdm版本到4.59.0:使用 pip install tqdm==4.59.0 命令安装4.59.0版本。
  3. 重新安装tqdm库:使用 pip uninstall tqdm 命令卸载tqdm库,然后使用 pip install tqdm 命令重新安装。

如果以上方法仍然无法解决问题,可以尝试查看tqdm库的官方文档或社区论坛,寻求更详细的解决方案。

解决Python中tqdm库'AttributeError: 'tqdm' object has no attribute 'last_print_t''错误

原文地址: https://www.cveoy.top/t/topic/nDeT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录