IN PYTHON, CHECK IF A DIRECTORY EXISTS AND CREATE IT IF NECESSARY

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
Python 
 1482  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. Mayank Tripathi

    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. Leonardo Lazzaro

    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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!