expanded = os.path.expanduser(dirpath)
if not os.path.isdir(expanded):
    if os.path.lexists(expanded):
        raise IOError(errno.EEXISTS, 'Path is a file, not a dir', expanded)
os.makedirs(expanded)
return os.path.join(expanded, filename)
Choosing a Path for Python File Access