Python代码:将文件夹打包成一个.tar.gz文件并使用经典进度条
Python代码:将文件夹打包成一个.tar.gz文件并使用经典进度条
以下代码使用Python将指定文件夹下的所有文件打包成一个.tar.gz文件,并使用alive_progress库的经典进度条显示压缩进度。
import os
import subprocess
from alive_progress import alive_bar, classic_spinner
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, spinner=classic_spinner, 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)
使用方法:
- 确保已安装
alive_progress库:pip install alive-progress - 将代码中的
source_dir和output_dir替换为需要压缩的源文件夹路径和输出文件夹路径 - 运行代码
代码说明:
pack_files函数接收源文件夹路径和输出文件夹路径作为参数- 函数首先检查源目录和输出目录是否存在
- 然后计算源文件夹中的文件总数
- 使用
alive_bar创建经典进度条并设置标题为'压缩进度' - 遍历源文件夹,对每个文件进行处理:
- 如果是文件夹,则使用
tar命令打包并压缩成tar.gz格式 - 如果是文件,则使用
pigz进行压缩
- 如果是文件夹,则使用
- 在每个文件处理完成后,更新进度条
注意事项:
- 确保
pigz已安装在系统中 - 代码中使用
subprocess.run执行系统命令,需要管理员权限 - 压缩后的文件将保存在
output_dir文件夹中
代码改进:
- 可以根据需要修改进度条样式,例如使用
alive_bar的其他进度条样式 - 可以添加错误处理机制,例如捕获压缩过程中的错误
- 可以添加日志记录功能,方便调试和记录压缩过程
希望这篇文章对您有所帮助!
原文地址: https://www.cveoy.top/t/topic/nDfC 著作权归作者所有。请勿转载和采集!