Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save achillesrasquinha/22e936bd562dffabbf6a2ea824edc2df to your computer and use it in GitHub Desktop.
Save achillesrasquinha/22e936bd562dffabbf6a2ea824edc2df to your computer and use it in GitHub Desktop.
Make files/directories using a Python dict.

Make Files/Directories using a Python Dict

Script

# imports - standard imports
import os
import os.path as osp
import errno
import collections

# imports - compatibility imports
import six

def write(fname, data = None, force = False):
    fname = str(fname)
    
    if not osp.exists(fname) or force:
        with open(fname, "w") as f:
            if data:
                f.write(data)

def makedirs(dirs, exist_ok = False):
    dirs = str(dirs)
    
    try:
        os.makedirs(dirs)
    except OSError as e:
        if not exist_ok or e.errno != errno.EEXIST:
            raise

def maketree(tree, location = os.getcwd(), exist_ok = False):
    location = str(location)
    
    for directory, value in six.iteritems(tree):
        path = osp.join(location, directory)
        makedirs(path, exist_ok = exist_ok)

        if isinstance(value, collections.Mapping):
            maketree(value, path, exist_ok = exist_ok)
        else:
            if value:
                path = osp.join(path, value)
                write(path, force = not exist_ok)

Example

>>> tree = dict(foo = dict(bar = "baz"))
>>> maketree(tree)

Output

$ tree foo
➜ tree foo       
foo
└── bar
   └── baz

1 directory, 1 file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment