【Python】 路径字典格式化


代码段


from functools import reduce
import os


def get_directory_structure(rootdir):
"""
Creates a nested dictionary that represents the folder structure of rootdir
"""
dir = {}
rootdir = rootdir.rstrip(os.sep)
start = rootdir.rfind(os.sep) + 1
for path, dirs, files in os.walk(rootdir):
folders = path[start:].split(os.sep)
subdir = dict.fromkeys(files)
parent = reduce(dict.get, folders[:-1], dir)
print(subdir)
parent[folders[-1]] = subdir
return dir


print(get_directory_structure(r"C:\Users\MZG\Desktop\MzgExercise"))


效果图:


 

 

 

 

 







posted @ 2021-04-20 09:40  情调丶  阅读(157)  评论(0编辑  收藏  举报