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?
Leonardo Lazzaro
03-Dec-2016Anonymous User
15-May-2015