How to Create Directory If It Does Not Exist in Python

Here are two ways to create a directory if it does not exist in Python:

  1. Using os.makedirs() and os.path.exists()
  2. Using isdir() and makedirs()

Create Directory If It Does Not Exist in Python

Method 1: Using os.makedirs() and os.path.exists() methods

The os.makedirs() method creates all intermediate-level directories. 

To check if a directory exists, use the “os.path.exists()” function. If the directory exists, then it will throw a FileExistsError exception.

Example

Before creating a directory, our directory looks like this:

Using os.makedirs() and os.path.exists() methods

Run the below code.

import os


def create_recursive_dir(dir_path):
  if not os.path.exists(dir_path):
    os.makedirs(dir_path)


create_recursive_dir(
   "/Users/krunallathiya/Desktop/Code/pythonenv/newdir/folder")

Output

Using os.makedirs()

Example 2: Using “exist_ok” argument of the makedirs() function

The makedirs() function accepts the exist_ok argument, which prevents the function from raising an error by setting it to True if the directory already exists.

To avoid FileExistsError, either the os.path.exists() function or exist_ok parameter.

import os

def create_recursive_dir(dir_path):
  os.makedirs(dir_path, exist_ok=True)

create_recursive_dir("/Users/krunallathiya/Desktop/Code/R/sf/match")

If you rerun this code, it won’t throw any error. However, if you set the exist_ok = False, it throws FileExistsError.

import os

def create_recursive_dir(dir_path):
  os.makedirs(dir_path, exist_ok=False)

create_recursive_dir("/Users/krunallathiya/Desktop/Code/R/sf/match")

Output

FileExistsError: [Errno 17] File exists: '/Users/krunallathiya/Desktop/Code/R/sf/match'

Either set make_exist = True or use the os.path.exists() function to avoid FileExistsError.

Method 2: Using isdir() and makedirs() methods

import os


def create_recursive_dir(dir_path):
  if not os.path.isdir(dir_path):
    os.makedirs(dir_path)


create_recursive_dir(
 "/Users/krunallathiya/Desktop/Code/pythonenv/newdir/folder2")

Output

Using isdir() and makedirs() methods

That’s it.

1 thought on “How to Create Directory If It Does Not Exist in Python”

Leave a Comment

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