python字典与列表结合,生成文件与路径的关系树,并遍历生成器打印出对应关系

文件夹目录结构
在这里插入图片描述

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"]
          }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值