2013-10-22 118 views
1

我试图构建一个字典,看起来像这样一本字典:建立从目录结构

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 

我敢肯定,我错过细节...

+0

我建议使用替代子目录名称作为键,一个键“项目”,它映射到子目录列表。你会避免一些恼人的冲突。 – Noctua

+0

您制定它的方式,不活动的节点将是未出现的文件? – Noctua

+0

我对此表示欢迎。我仍然不知道如何写它。这是一个过于复杂的Web应用程序,用于执行我已经负责创建的文件修复。 [活动意味着它存在于文件系统中,非活动意味着文件已从系统中删除,但存在于存档中 - 这是一个备份服务器,它也有磁带备份] – MTeck

回答

1

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

每个文件都有一个字典项,如:

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

任何目录都有类似的字典项:

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'} 
+0

我将如何使用它来循环多个列表? (将/ var /的所有内容都写入字典) – MTeck

+0

'var_dict = PathToDict('/ var')'会将'/ var'的所有后代变为一个字典。 –

+0

这依赖于实际上具有文件的系统......在第二部分中,它是系统中实际不存在的文件的列表... – MTeck