In Python, check if a directory exists and create it if necessary

Total Post:135

Points:947
Python 
 1839  View(s)
Ratings:
Rate this:
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?
  1. Post:397

    Points:3117
    Re: In Python, check if a directory exists and create it if necessary

    Try the os.path.exists function

    if not os.path.exists(dir):
        os.mkdir(dir)

  1. Post:1

    Points:7
    Re: In Python, check if a directory exists and create it if necessary

    For a more in depth information on how to check if a file exists in python check this link here http://tutorials.technology/tutorials/08-How-to-check-that-file-exists-with-Python.html


    Mayank Tripathi answer is right, but os.path.exists could return True for a file and not a directory.

      Modified On Apr-11-2018 05:47:20 AM

Answer