Python 遍历文件夹

import os
from settings import dir_dict


def traverse(dir):
    for ele_dir in dir:
        if ele_dir[1]:
            for i in ele_dir[1]:
                dir_name = os.path.join(ele_dir[0], i)
                traverse(os.walk(dir_name))
        else:
            print(ele_dir[0])
            tmp_list = ele_dir[0].split("\\")
            dir_dict[len(tmp_list)] = ele_dir[0]        # 字典的键唯一, 同样层级的文件夹只会保留一个


def get_deepest_dir(path):
    ret = os.walk(path)

    traverse(ret)
    print("-------------------")
    for k in sorted(dir_dict)[::-1]:
        print(k, "\t", dir_dict[k])


if __name__ == '__main__':
    path = r"文件夹地址"
    get_deepest_dir(path)
    del dir_dict
posted @ 2021-03-01 16:07  道友请留步W  阅读(108)  评论(0编辑  收藏  举报