Python : Create directory if directory/folder(s) don’t exists already

In Python, I have to make sure, for quite a lot time, that some directory path exists before I can do some operation on that. So, here is the code in python that make sure some directory path or folder path exists before we do something on that directory.

It will create all the directories in the path, if they are not exists

import os, errno

def make_sure_dir_exists(path):
    if not os.path.exists(dir):
        try:
            os.makedirs(path)
        except OSError as exc: # Python >2.5
            if exc.errno == errno.EEXIST:
                pass
            else: raise

Leave a comment