#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''
一级文件夹 Test_path
二级文件夹 2016 所含文件：Chinse.docx，math.xlsx
二级文件夹 2017 所含文件：1.txt, 2.txt, 3.txt, English.txt
二级文件夹 2018 所含文件：1.txt, 2.txt, 3.txt, Hello.txt
'''

import os

path = "D:\\Test_path" # 也可采用 r" D:\Test_path" 或者是"D:/Test_path"

# 方法一：使用 os.walk 方法遍历所有文件
for root,dirs,files in os.walk(path):
    for file in files:
        # 使用join函数将文件名称和文件所在根目录连接起来
        print(os.path.join(root, file))

# 输出为：
'''
D:\Test_path\2016\Chinese.docx
D:\Test_path\2016\math.xlsx
D:\Test_path\2017\1.txt
D:\Test_path\2017\2.txt
D:\Test_path\2017\3.txt
D:\Test_path\2017\English.txt
D:\Test_path\2018\1.txt
D:\Test_path\2018\2.txt
D:\Test_path\2018\3.txt
D:\Test_path\2018\Hello.txt
'''


# 方法二：使用 os.walk 方法遍历所有目录
for root,dirs,files in os.walk(path):
    for dir in dirs:
        # 使用join函数将当前目录和文件所在根目录连接起来
        print(os.path.join(root, dir))

# 输出为：
'''
D:\Test_path\2016
D:\Test_path\2017
D:\Test_path\2018
'''

# 方法三：使用os.listdir列出输出所有文件和目录，需要判断，如果是目录就递归一下
def get_filePath(path):
    '''
    input: 文件路径path
    '''
    file_or_dir = os.listdir(path)
    for file_dir in file_or_dir:
        file_or_dir_path = os.path.join(path,file_dir)
        # 判断该路径是不是路径，如果是，递归调用
        if os.path.isdir(file_or_dir_path):
            print('Path: '+ file_or_dir_path)
            #递归
            get_filePath(file_or_dir_path)
        else:
            print('File: '+ file_or_dir_path)
get_filePath(path)


# 输出为：
'''
Path: D:\Test_path\2016
File: D:\Test_path\2016\Chinese.docx
File: D:\Test_path\2016\math.xlsx
Path: D:\Test_path\2017
File: D:\Test_path\2017\1.txt
File: D:\Test_path\2017\2.txt
File: D:\Test_path\2017\3.txt
File: D:\Test_path\2017\English.txt
Path: D:\Test_path\2018
File: D:\Test_path\2018\1.txt
File: D:\Test_path\2018\2.txt
File: D:\Test_path\2018\3.txt
File: D:\Test_path\2018\Hello.txt
'''