【问题标题】:store directory structure in nested dictionary in python在python的嵌套字典中存储目录结构
【发布时间】:2017-09-25 08:21:58
【问题描述】:

我正在尝试将目录结构存储在嵌套字典中。 目录树

├── dirA
│   ├── dirB1
│   │   └── file1.txt
│   └── dirB2
│       └── file2.txt
├── templates
│   ├── base.html
│   └── report.html
└── test.py  

嵌套字典是这样的:

{'dirs': {'.': {'dirs': {'dirA': {'dirs': {'dirB1': {'dirs': {},
                                                     'files': ['file1.txt']}, 
                                           'dirB2': {'dirs': {},
                                                     'files':['file2.txt']}
                                                     }                                          
                                  'files': []}, 
                         'templates':{'dirs':{},
                                  'files':['base.html', 'report.html']}},
         'files': ['test.py']}},
 'files': []}

我认为递归是一个很好的方法。

import os                                                 
import pprint              

pp = pprint.PrettyPrinter()
def path_to_dict(path): 
    d = {'dirs':{},'files':[]}
    name = os.path.basename(path)
    if os.path.isdir(path):
        if name not in d['dirs']:
            d['dirs'][name] = {'dirs':{},'files':[]}
        for x in os.listdir(path):
            d['dirs'][name]= path_to_dict(os.path.join(path,x))                                                 
    else:                  
        d['files'].append(name)        
    return d               

mydict = path_to_dict('.')
pp.pprint(mydict)

结果与我的预期不同。但是不知道递归中哪一步出错了。

【问题讨论】:

  • 我知道为什么这段代码会输出错误的结果。 d = {'dirs':{},'files':[]} 将重置字典项。
  • 为什么需要这个? os.walk() 在遍历目录结构时通常更容易使用。
  • @MartinEvans 是的,os.walk() 可以通过目录。但我正在尝试查找目录结构。

标签: python dictionary recursion


【解决方案1】:

您在每次调用时创建 dict 对象,您需要在每次调用时传递其 d['dirs'][name] 值以允许其递归构造:

import os
import pprint

pp = pprint.PrettyPrinter()

def path_to_dict(path, d):

    name = os.path.basename(path)

    if os.path.isdir(path):
        if name not in d['dirs']:
            d['dirs'][name] = {'dirs':{},'files':[]}
        for x in os.listdir(path):
            path_to_dict(os.path.join(path,x), d['dirs'][name])
    else:
        d['files'].append(name)
    return d


mydict = path_to_dict('.', d = {'dirs':{},'files':[]})

pp.pprint(mydict)

【讨论】:

    猜你喜欢
    • 2021-06-03
    • 2021-04-12
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2022-11-27
    • 2011-10-23
    相关资源
    最近更新 更多