Users Pricing

forum

Home Forums In Python, check if a directory exists and create it if necessary – MindStick

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

Anonymous User 3211 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?

2 Answers

Markdown for AI

A clean, structured version of this page for AI assistants and LLMs.

Open .md