How can I check the file going to be written exists in the directory, and if not , How can I create directory in Python. I already tried this:
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)
But I missed os.path.exists ,and now I have:
def ensure_dir(file_path):
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory)
Can I make this happen automatically, is there an "open" flag for the same?