为代码增加功能所有压缩任务完成后对output_dir目录下文件名中有mp4的mp4不是文件后缀移除文件名中的mp4注意不是移除文件import osimport subprocessfrom alive_progress import alive_bar config_handlerdef pack_filessource_dir output_dir # 检查源目录和输出目录是否存在
import os import subprocess from alive_progress import alive_bar, config_handler
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
# 统计文件和文件夹的数量
file_count = 0
dir_count = 0
for entry in os.scandir(source_dir):
if entry.is_file():
file_count += 1
elif entry.is_dir():
dir_count += 1
# 设置进度条样式
config_handler.set_global(length=40, spinner="classic", bar="classic", enrich_print=True)
total_count = file_count + dir_count
with alive_bar(total_count, title='压缩进度') as bar:
# 处理文件和文件夹
for entry in os.scandir(source_dir):
if entry.is_file():
# 获取需要压缩的文件路径
file_path = os.path.relpath(entry.path, source_dir)
# 拼接输出文件路径
output_file = os.path.join(output_dir, f'{entry.name}.gz')
# 使用tar和pigz命令压缩文件
subprocess.run(['tar', '-I', 'pigz', '-cf', output_file, file_path], cwd=source_dir)
elif entry.is_dir():
# 获取需要压缩的文件夹路径
dir_path = os.path.relpath(entry.path, source_dir)
# 拼接输出文件路径
output_file = os.path.join(output_dir, f'{entry.name}.tar.gz')
# 使用tar和pigz命令打包并压缩文件夹
subprocess.run(['tar', '-I', 'pigz', '-cf', output_file, dir_path], cwd=source_dir)
# 更新进度条
bar()
# 遍历输出目录,移除文件名中的'.mp4'
for entry in os.scandir(output_dir):
if entry.is_file() and '.mp4' in entry.name:
new_name = entry.name.replace('.mp4', '')
os.rename(entry.path, os.path.join(output_dir, new_name))
路径
source_dir = '/home/115/up' output_dir = '/home/115/app' pack_files(source_dir, output_dir
原文地址: http://www.cveoy.top/t/topic/dfHI 著作权归作者所有。请勿转载和采集!