Automatically creating directories with file output [duplicate] Automatically creating directories with file output [duplicate] python python

Automatically creating directories with file output [duplicate]


The os.makedirs function does this. Try the following:

import osimport errnofilename = "/foo/bar/baz.txt"if not os.path.exists(os.path.dirname(filename)):    try:        os.makedirs(os.path.dirname(filename))    except OSError as exc: # Guard against race condition        if exc.errno != errno.EEXIST:            raisewith open(filename, "w") as f:    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import osfilename = "/foo/bar/baz.txt"os.makedirs(os.path.dirname(filename), exist_ok=True)with open(filename, "w") as f:    f.write("FOOBAR")


matomo