views:

316

answers:

1

Hi I need a simple function to create a path in Python where the parent may or may not exist.

From python documentation os.makedirs will fail if one of the parents exists.

I have written the below method as which works by makes as many sub directories as necessary.

Does this look efficient?

def create_path(path):
    import os.path as os_path
    paths_to_create = []
    while not os_path.lexists(path):
        paths_to_create.insert(0, path)
        head,tail = os_path.split(path)
        if len(tail.strip())==0: # Just incase path ends with a / or \
            path = head
            head,tail = os_path.split(path)
        path = head

    for path in paths_to_create:
        os.mkdir(path)

Regards

Mark

+3  A: 

From python documentation os.makedirs will fail if one of the parents exists.

os.makedirs will fail if the directory itself already exists. It won't fail if just any of the parent directories already exists.

sth
excellent, thanks for the update!
Mark Ellul