zip_with_progress.md 3.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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
# Python 文件夹压缩

使用 shutil 对文件夹进行zip压缩,压缩过程显示进度条

```python
# -*- coding: UTF-8 -*-
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):
        # TODO(You): 进度条显示
    
    # 调用shutil.make_archive时,临时替换其 logger 参数,用来显示进度条
    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()
```

请选出下列能**正确**实现这一功能的选项。

## template

```python
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()
```

## 答案

```python
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)
```

## 选项

### A

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

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

### B

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

### C

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

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