Wednesday, September 22, 2010

Python : Create path or directories, if not exist

I came across to this question very often, that how to create a directory structure, if I know the exact path of file or directory hierarchy. That is not difficult but very time consuming if you don't know where to find the resources. Let go to code we need,

def assure_path_exists(path):
        dir = os.path.dirname(path)
        if not os.path.exists(dir):
                os.makedirs(dir)
first line define python function/module assure_path_exists, which take one argument "path" of file or directory.
second line, ensure path contain directory only. it strips filename, if there is any.
third line, checks for whether this path (pointed by dir), exists or not
forth line, if path pointed by dir not exists, we create that path through os.makedirs

Done!!!

No comments: