# Python 文件遍历(2)

遍历一个文件夹下的所有子文件夹，并返回所有'config.json'文件的绝对路径列表

```python
# -*- coding: UTF-8 -*-
import os

def retrieve_file_paths(dir_name):
    file_paths = []
    abs_dir_name = os.path.abspath(dir_name)

    # TODO(You): 请在此实现遍历代码

    return file_paths

if __name__ == '__main__':
    file_paths = retrieve_file_paths('./')
    print(file_paths)
```

以下实现，**错误**的代码是？

## template

```python
import os


def retrieve_file_paths(dir_name):
    file_paths = []
    abs_dir_name = os.path.abspath(dir_name)
    for root, directories, files in os.walk(abs_dir_name):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            file_paths.append(file_path)
    return file_paths

if __name__ == '__main__':
    file_paths = retrieve_file_paths('./')
    print(file_paths)
```

## 答案

```python
for base, dirs, files in os.walk(abs_dir_name):
    for dir in dirs:
        cfg_file = os.path.join(base, dir, 'config.json')
        if os.path.exists(cfg_file):
            file_paths.append(cfg_file)
```

## 选项

### A

```python
for base, dirs, files in os.walk(abs_dir_name):
    for file_name in files:
        if file_name == 'config.json':
            file_path = os.path.join(base, file_name)
            file_paths.append(file_path)
```

### B

```python
cfg_file = os.path.join(abs_dir_name, 'config.json')
if os.path.exists(cfg_file):
    file_paths.append(cfg_file)

for base, dirs, files in os.walk(abs_dir_name):
    for dir in dirs:
        cfg_file = os.path.join(base, dir, 'config.json')
        if os.path.exists(cfg_file):
            file_paths.append(cfg_file)
```

### C

```python
for base, dirs, files in os.walk(abs_dir_name):
    cfg_file = os.path.join(base, 'config.json')
    if os.path.exists(cfg_file):
        file_paths.append(cfg_file)
```
