Reputation: 1688
I'm trying to build a dictionary that looks like this:
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
}
}
I need it to be built by two pieces... The first needs to be from the file system where everything is 'active'. The second needs to come from a listing of full paths of files where everything is inactive.
So...
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
I'm sure I'm missing details...
Upvotes: 1
Views: 3216
Reputation: 168866
Here's one way to get the active files. I found it easier to recurse than to use os.walk()
's iterative data. You may uncomment the result['stat']
line if you need to preserve more information than file type.
Every file has a dict entry like:
filename : { 'active' : True,
'full_path' = '/path/to/filename',
'type' : 'f' }
Every directory has a dict entry like:
dirname : { 'active' : True,
'full_path' = '/path/to/dirname',
'type' : 'd',
items = { 'itemname' : {...}, ... } }
Here you go:
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]))
Result:
{'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'}
Upvotes: 5