forum

Home / DeveloperSection / Forums / In Python, check if a directory exists and create it if necessary

In Python, check if a directory exists and create it if necessary

Anonymous User 2632 15-May-2015
What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:
filename = "/my/directory/filename.txt"
dir = os.path.dirname(filename)
try:
    os.stat(dir)
except:
    os.mkdir(dir)       
f = file(filename)
Somehow, I missed os.path.exists . This is what I have now:
def ensure_dir(f):
    d = os.path.dirname(f)
    if not os.path.exists(d):
        os.makedirs(d)
Is there a flag for "open", that makes this happen automatically?

Updated on 03-Dec-2016
I am a content writter !

Can you answer this question?


Answer

2 Answers

Liked By