How can I safely create a nested directory in Python?

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:

import os

file_path = “/my/directory/filename.txt”
directory = os.path.dirname(file_path)

try:
os.stat(directory)
except:
os.mkdir(directory)

f = file(filename)

Somehow, I missed os.path.exists (thanks kanja, Blair, and Douglas). This is what I have now:

def ensure_dir(file_path):
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory)

Is there a flag for “open”, that makes this happen automatically?

#python

3 Likes1.35 GEEK