Q:

Managing the paths of a directory tree in python

I have a python script that keeps track of several directory names as individual variables. Some of these directories may exist, while others may need to be created at execution time.
For example, if I have this directory tree:
./top
     /a
       /a1
       /a2
     /b
       /b1
     /c

then I currently track all the directory path names with individual variables:
top_path = os.path.join(os.curdir, 'top')
a_path = os.path.join(top_path, 'a')
# etc...

but it would be nice to organise them in some way that respects the directory tree, if not actual OS directory support.
Is there some standard way of managing a directory tree (or any tree of variables) in python? Or should I just store everything in a nested list or tuple, or even make my own class? Something with a nice API like top.a.a1 returning './top/a/a1' would be great.

A:

How about a dict-of-dicts? Something like:
tree = {
       'top': {
              'a': {
                   'path': a_pathvar,
                   'a1':
                   'a2':
               }
               'b': {
                    'path':  b_pathvar,
                }
         }
       }

Then you could easily access the path variable for a1 with tree['top']['a']['a1']['path']. You can easily create this tree structure with a single line of code:
def tree(): return defaultdict(tree)

A nice property of this structure is that intermediate keys need not exist if you try to create a path:
tree['top']['a']['long']['tree']['path'] = path_var

This will automatically create the intermediate keys for you
This page goes into more detail.

