Python 使用 alive_progress 库显示文件压缩进度条

本示例代码使用 Python 的 alive_progress 库,在压缩文件时显示动态进度条,让用户直观地了解压缩进度。

import os
import subprocess
from alive_progress import alive_bar


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 alive_bar(total_files, title='压缩进度') as bar:

        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])
                    bar.text(f'已将文件夹{file_path}打包压缩到{tar_file}')
                else:
                    # 处理文件,使用pigz进行压缩
                    subprocess.run(['pigz', '-c', file_path],
                                   stdout=open(output_file, 'wb'))
                    bar.text(f'已将文件{file_path}压缩到{output_file}')

                # 更新外层进度条
                bar()


# 路径
# 替换为你的实际路径
source_dir = '/home/115/up'
output_dir = '/home/115/app'
pack_files(source_dir, output_dir)

使用方法:

  1. 安装 alive_progress 库:
pip install alive-progress
  1. 将代码中的 source_diroutput_dir 替换为你的实际目录路径,并运行代码。

代码解释:

  1. 使用 alive_bar 函数创建一个进度条,并设置标题为 压缩进度
  2. 使用 os.walk 函数遍历 source_dir 目录下的所有文件和文件夹。
  3. 对于每个文件,判断是否为文件夹,并使用 tarpigz 命令进行压缩。
  4. 使用 bar.text 函数更新进度条的显示内容,显示已压缩的文件或文件夹信息。
  5. 使用 bar() 函数更新进度条进度,每压缩完一个文件或文件夹,进度条就会前进一步。

效果:

在运行代码时,控制台将会显示一个动态的进度条,显示正在压缩的文件或文件夹以及压缩进度。

注意:

  • 该代码需要 tarpigz 命令,请确保你的系统已经安装了这些命令。
  • 如果你需要修改压缩格式或压缩方式,请修改代码中的命令参数。
  • 可以根据自己的需求修改进度条的样式和显示内容。

通过使用 alive_progress 库,可以更直观地了解文件压缩进度,提高代码的可读性和用户体验。

Python 使用 alive_progress 库显示文件压缩进度条

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

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