Computer >> Computer tutorials >  >> Programming >> Python

How can I create a python directory if it does not exist?


When programming in python, using Idiomatic python is normally the way to go. One of python idioms is EAFP: Easier to ask for forgiveness than permission. So try creating a directory, if it exists you'll get an error you can catch. 

example

import os, errno
try:
    os.makedirs('my_folder')
except OSError as e:
    # If error is not already exists, then raise the error else continue
    if e.errno != errno.EEXIST:
        raise
# Now do what you want with my_folder