zip_with_progress.py 1.1 KB
Newer Older
F
feilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
# -*- coding: UTF-8 -*-
# 作者:幻灰龙
# 标题:Python 文件夹压缩
# 描述:使用 shutil 对文件夹进行zip压缩,压缩过程显示进度条

import os
import shutil
import logging
from progress.bar import IncrementalBar
logger = logging.getLogger(__name__)


def count_files_in_dir(dir):
    totalFiles = 0
    for base, dirs, files in os.walk(dir):
        totalFiles += len(files)
    return totalFiles


def zip_with_progress(dir_path, zip_file):
    bar = None
    total_files = count_files_in_dir(dir_path)

    def progress(*args, **kwargs):
        if not args[0].startswith('adding'):
            return

        nonlocal bar, total_files
        if bar is None:
            print('@开始压缩:{}'.format(zip_file))
            bar = IncrementalBar('正在压缩:', max=total_files)
        bar.next(1)

    old_info = logger.info
    logger.info = lambda *args, **kwargs: progress(*args, **kwargs)

    shutil.make_archive(dir_path, 'zip', dir_path, logger=logger)
    logger.info = old_info

    if bar is not None:
        bar.finish()


if __name__ == '__main__':
    zip_with_progress('./', '/tmp/test_file_zip.zip')
    print()