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?
Check os.makedirs: (It makes sure the complete path exists.)
To handle the fact the directory might exist, catch OSError. (If exist_ok is False (the default), an OSError is raised if the target directory already exists.)
Starting from Python 3.5,
pathlib.Path.mkdir
has anexist_ok
flag:This recursively creates the directory and does not raise an exception if the directory already exists.
(just as
os.makedirs
got anexist_ok
flag starting from python 3.2 e.gos.makedirs(path, exist_ok=True)
)Use this command check and create dir
In Python3,
os.makedirs
supports settingexist_ok
. The default setting isFalse
, which means anOSError
will be raised if the target directory already exists. By settingexist_ok
toTrue
,OSError
(directory exists) will be ignored and the directory will not be created.In Python2,
os.makedirs
doesn't support settingexist_ok
. You can use the approach in heikki-toivonen's answer:Try the
os.path.exists
functionWhy not use subprocess module if running on a machine that supports shell languages? Works on python 2.7 and python 3.6
Should do the trick on most systems.