文件夹目录结构
import os
from copy import deepcopy
def get_relation_tree(path):
finger_files_dict, people_fingers_dict, people_name_befor= {},{},''
for root, dirs, files in os.walk(path):
if files:
dir_list = root.split("\\")
people_name, finger_name = dir_list[-2], dir_list[-1]
if people_name != people_name_befor: # 如果人名改变了,清空finger_files_dict
finger_files_dict.clear()
people_name_befor = deepcopy(people_name)
finger_files_dict[finger_name] = files
temp_dict = deepcopy(finger_files_dict) # 深拷贝,防止已经存到people_fingers_dict的数据被覆盖
people_fingers_dict[people_name] = temp_dict
print(people_fingers_dict)
return people_fingers_dict
def walk_relation_tree(dict):
for people in dict.keys():
finger_files_dict = dict[people]
for finger in finger_files_dict.keys():
for file in finger_files_dict[finger]:
yield people,finger,file
relation_tree = get_relation_tree(r"D:\project\Python project\学习\demo_file")
for people,finger,file in walk_relation_tree(relation_tree):
print(f"people_name:{people} | finger_name:{finger} | file_name:{file}")
get_relation_tree()生成文件与路径的关系树
{
"001":{
"L1":["1.bmp","2.bmp","3.bmp"]
"L2":["4.bmp","5.bmp","6.bmp"]
"R3":["7.bmp","8.bmp","9.bmp"]
}
"002":{
"L1":["10.bmp","11.bmp","12.bmp"]
"L2":["13.bmp","14.bmp","15.bmp"]
"R3":["16.bmp","17.bmp","18.bmp"]
}
"003":{
"L1":["19.bmp","20.bmp","21.bmp"]
"L2":["22.bmp","23.bmp","24.bmp"]
"R3":["25.bmp","26.bmp","27.bmp"]
}
}