How to Create Directory If Not Exists in Python

To create a directory that does not exist in Python, you can combine the “os.path.exists()” and “os.makedirs()” methods. The os.path.exists() function checks if a directory exists and returns True or False, and then the os.makedirs() function creates one if it does not exist.

Example 1: Using the os.path.exists() and makedirs() function

import os path = '/Users/krunal/Desktop/code/pyt/database' 
# Check whether the specified path exists or not 
isExist = os.path.exists(path) 
print(isExist)

Output

True

It returns True, which means it does exist.

Example 2:  Let’s take a scenario where the path does not exist.

import os 

path = '/Users/krunal/Desktop/code/database'

isExist = os.path.exists(path) 
print(isExist)

path = '/Users/krunal/Desktop/code/pyt/database/app.py'

isExist = os.path.exists(path)

print(isExist)

Output

False

Here, we can safely create a new directory of the specified path because it does not exist.

Use the os.makedirs() function to create a new directory.

But before that, we will use the if not operator to check if it does not exist and create a new directory.

import os 

path = '/Users/krunal/Desktop/code/database' 

isExist = os.path.exists(path)

if not isExist:
  os.makedirs(path) 
  print("The new directory is created!")

Output

The new directory is created!

That’s it. We successfully created a directory which does not exist previously.

If you rerun the code, it won’t create any further directories because now it exists.

The default mode is 0o777 (octal). On some systems, the mode is ignored.

Where it is used, the current umask value is first masked out. Then, if exist_ok is False (the default), an OSError is raised if the target directory already exists.

Example 3: Passing exists_ok argument to the makedirs() function

The os.makedirs() function takes the exists_ok argument as an optional argument because it has a default value; by default, exists_ok is set to False.

For example, using the makedirs() function to create an existing path will not be OK.

To prevent an error message from being thrown, set the exists_ok to True when calling makedirs().

import os

path = '/Users/krunal/Desktop/code/database' 

os.makedirs(path, exist_ok=False) 

print("The new directory is created!")

So that’s how you easily create directories and subdirectories in Python with the makedirs() function.

Conclusion

Use the combination of the os.path.exists() and os.makedirs() functions to check if the directory exists, and if it does not, create a new directory in Python.

Further reading

How to create a recursive directory If not exists in Python

How to create a folder in the current directory in Python

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.