从目录结构构建字典

MTe*_*eck 1 python tree

我正在尝试构建一个如下所示的字典:

nodes = {
    'var': {
        'type': 'd',
        'full_path': '/var'
        'active': True
        'www': {
            'type': 'd',
            'full_path': '/var/www',
            'active': True
            'index.html': {
                'type': 'f',
                'full_path': '/var/www/index.html',
                'active': False
            }
        'log': {
            'type': 'd',
            'full_path': '/var/log',
            'active': False
        }
    }
    'srv': {
        'type': 'd',
        'full_path': '/srv',
        'active': True
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要它由两部分构建......第一个需要来自所有内容都处于“活动”状态的文件系统。第二个需要来自所有内容均处于非活动状态的文件的完整路径列表。

所以...

nodes = {}
for f, d, r in os.walk(root_path):
    # append active items to nodes
for f in os.system(command_that_gets_files)
    # append inactive items to nodes; not overwriting active
Run Code Online (Sandbox Code Playgroud)

我确信我错过了细节......

Rob*_*obᵩ 5

这是获取活动文件的一种方法。我发现递归比使用os.walk()的迭代数据更容易。result['stat']如果您需要保留文件类型以外的更多信息,您可以取消注释该行。

每个文件都有一个字典条目,例如:

filename : { 'active' : True,
             'full_path' = '/path/to/filename',
             'type' : 'f' }
Run Code Online (Sandbox Code Playgroud)

每个目录都有一个字典条目,例如:

dirname : { 'active' : True,
            'full_path' = '/path/to/dirname',
             'type' : 'd',
             items = { 'itemname' : {...}, ... } }
Run Code Online (Sandbox Code Playgroud)

干得好:

import sys
import os
from stat import *
import pprint

def PathToDict(path):
    st = os.stat(path)
    result = {}
    result['active'] = True
    #result['stat'] = st
    result['full_path'] = path
    if S_ISDIR(st.st_mode):
        result['type'] = 'd'
        result['items'] = {
            name : PathToDict(path+'/'+name)
            for name in os.listdir(path)}
    else:
        result['type'] = 'f'
    return result


pprint.pprint(PathToDict(sys.argv[1]))
Run Code Online (Sandbox Code Playgroud)

结果:

{'active': True,
 'full_path': '/tmp/x',
 'items': {'var': {'active': True,
                   'full_path': '/tmp/x/var',
                   'items': {'log': {'active': True,
                                     'full_path': '/tmp/x/var/log',
                                     'items': {},
                                     'type': 'd'},
                             'www': {'active': True,
                                     'full_path': '/tmp/x/var/www',
                                     'items': {'index.html': {'active': True,
                                                              'full_path': '/tmp/x/var/www/index.html',
                                                              'type': 'f'}},
                                     'type': 'd'}},
                   'type': 'd'}},
 'type': 'd'}
Run Code Online (Sandbox Code Playgroud)