2

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.

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.