从目录结构构建字典

时间:2013-10-22 15:23:43

标签: 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
    }
}

我需要它由两部分构建......第一部分需要来自文件系统,其中一切都是活跃的'。第二个需要来自一系列文件的列表,其中一切都是无效的。

因此...

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

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

1 个答案:

答案 0 :(得分:1)

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

每个文件都有一个dict条目,如:

filename : { 'active' : True,
             'full_path' = '/path/to/filename',
             'type' : 'f' }

每个目录都有一个dict条目,如:

dirname : { 'active' : True,
            'full_path' = '/path/to/dirname',
             'type' : 'd',
             items = { 'itemname' : {...}, ... } }

你走了:

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]))

结果:

{'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'}
相关问题