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:


 1 Reply(s)
 560  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)

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

Follow MindStick