Home > DeveloperSection > Forums > In Python, check if a directory exists and create it if necessary
Chintoo Semi

Total Post:135

Points:947
Posted on    May-15-2015 12:03 AM

 Python Python 
Ratings:


 2 Reply(s)
 695  View(s)
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?


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    May-15-2015 8:30 AM

Try the os.path.exists function

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

Leonardo Lazzaro
Leonardo Lazzaro

Total Post:1

Points:7
Posted on    December-03-2016 11:46 AM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick