import os import subprocess from alive_progress import alive_bar, config_handler

def get_file_path(entry): '获取需要压缩的文件路径' return entry.path

def get_output_file(entry, output_dir): '拼接输出文件路径' if entry.is_file(): file_name, file_ext = os.path.splitext(entry.name) return os.path.join(output_dir, f'{file_name}.gz') elif entry.is_dir(): return os.path.join(output_dir, f'{entry.name}.tar.gz')

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 = get_file_path(entry)

            '获取输出文件路径'
            output_file = get_output_file(entry, output_dir)

            '使用pigz命令压缩文件'
            subprocess.run(['pigz', '-k', '-c', file_path], stdout=open(output_file, 'wb'))

        elif entry.is_dir():
            '获取需要压缩的文件夹路径'
            dir_path = entry.path

            '获取输出文件路径'
            output_file = get_output_file(entry, output_dir)

            '使用pigz命令打包并压缩文件夹'
            subprocess.run(['tar', '-I', 'pigz', '-cf', output_file, '-C', source_dir, entry.name])

        '更新进度条'
        bar()

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

Python 代码优化:减少重复代码,提高效率

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

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