---
title: "In Python, check if a directory exists and create it if necessary"  
description: "In Python, check if a directory exists and create it if necessary"  
author: "Anonymous User"  
published: 2015-05-15  
updated: 2016-12-03  
canonical: https://www.mindstick.com/forum/23229/in-python-check-if-a-directory-exists-and-create-it-if-necessary  
category: "python"  
tags: ["python"]  
reading_time: 1 minute  

---

# In Python, check if a directory exists and create it if necessary

What is the most elegant way to [check if](https://www.mindstick.com/forum/12878/how-to-check-if-an-asp-dot-net-file-upload-control-has-a-file-in-jquery) the [directory](https://www.mindstick.com/forum/226/how-to-get-application-directory-using-c-sharp-csharp) a [file](https://www.mindstick.com/articles/59/encrypting-and-decrypting-files-using-c-sharp) is going to be written to [exists](https://www.mindstick.com/forum/158947/how-do-you-use-the-exists-operator-to-check-for-the-existence-of-records-in-a-subquery), and if not, create the directory using [Python](https://www.mindstick.com/articles/75378/simple-yet-useful-tips-when-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](https://yourviews.mindstick.com/view/81402/it-s-liberals-vs-progressives-in-us-politics-now):

```
def ensure_dir(f):    d = os.path.dirname(f)    if not os.path.exists(d):        os.makedirs(d)
```

Is there a [flag](https://answers.mindstick.com/qa/34828/how-many-stars-were-on-the-original-american-flag) for "open", that makes this happen automatically?

## Replies

### Reply by Leonardo Lazzaro

For a more in depth information on how to [check](https://yourviews.mindstick.com/story/2248/never-forget-to-check-these-specifications-before-buying-a-mobile-phone) 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](https://www.mindstick.com/Account/11260) answer is right, but os.path.exists could return True for a file and not a directory.\
\

### Reply by Anonymous User

Try the os.path.exists function\

```
if not os.path.exists(dir):    os.mkdir(dir)
```


---

Original Source: https://www.mindstick.com/forum/23229/in-python-check-if-a-directory-exists-and-create-it-if-necessary

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
