How to Create a Folder in Python If It Does Not Already Exist

It is not uncommon when working with Python to need to create a new directory (or folder, if you are on a Windows platform).

In this blog post, we will walk through the steps necessary to create a new directory (folder) if one does not already exist using only Python code.

We will also touch on some of the pitfalls that can occur if you are not careful when creating new folders.

Creating New Folders in Python using os module

There are a few different ways that we can go about creating new folders in Python. The first way is to use the os module.

The os module provides us with many useful functions for interacting with the operating system. One such function is the os.makedirs function.

This function takes a single argument, which is the path of the directory (folder) that you would like to create.

Let’s walk through an example of how to use the os.makedirs function. We will start by importing the os module.

Then, we will define a variable called “new_folder_path” and set it equal to the path of the folder that we would like to create. Finally, we will call the os.makedirs function, passing in our “new_folder_path” variable as an argument.

import os new_folder_path = './new-folder' os.makedirs(new_folder_path)
Code language: Python (python)

Python script 1:

directory = os.path.dirname(out_dir) os.makedirs(directory, mode=0o777, exist_ok=True)
Code language: Python (python)

Python script 2:

import os # checking if the directory folder2 # exist or not. if not os.path.isdir("path/to/folder2"): # if the folder2 directory is # not present then create it. os.makedirs("path/to/folder2")
Code language: Python (python)

Python script 3:

import os os.makedirs(path, exist_ok=True)
Code language: Python (python)

os.makedirs as used above recursively creates the directory and does not raise an exception if the directory already exists. It has the optional exist_ok argument only if using Python 3.2+, with a default value of False.

Python script 4:

# Re-running does not overwrite existing directories and files; no errors. import os import errno def make_sure_path_exists(my_path): try: os.makedirs(my_path) except OSError as exception: if exception.errno != errno.EEXIST or not os.path.isdir(my_path): raise
Code language: Python (python)

Python script 5:

You can use os.listdir for this:

import os if 'dirName' in os.listdir('parentFolderPath') print('Directory Exists')
Code language: Python (python)

Creating folders using the os module is pretty straightforward. However, there are some potential issues that can arise if you are not careful when using this method.

One such issue has to do with permissions. If you do not have permission to create a new folder in the specified location, then an exception will be raised and your program will crash.

Another issue has to do with race conditions. If two programs try to create a folder with the same name at roughly the same time, it is possible for one of them to fail because the folder did not exist when it attempted to create it but did exist by the time it checked again (because the other program had already created it).

Fortunately, there is another way to create folders in Python that avoids these issues entirely.

Using the pathlib module

We can use the pathlib module (introduced in Python 3.4) instead of the os module.

The pathlib module provides an object-oriented interface for working with filesystem paths as Path objects similar to how strings are handled as string objects.

One advantage of using pathlib over os is that Path objects contain methods for creating directories (among other things).

This means that we don’t have to worry about potential permissions or race conditions issues when creating folders using pathlib since those concerns are handled internally by the Path object itself rather than by our code specifically.

Let’s take a look at how we would go about creating a folder using pathlib now:

from pathlib import Path # we need to import Path from pathlib #new_folder_path = Path('./new-folder') # define our Path object ## note: no trailing slash! important! # new_folder_path =Path('C:\python_dir\New_Folder') # windows users ## note: include trailing slash! important! #new_directory = new_folder_path/'sub-directory' # define subdirectory new_directory2 =Path('C:\\python_dir\\New_Folder').joinpath('sub-directory') # windows alternative try: if not new_directory2.parent.exists(): new_directory2.parent.mkdir(parents=True) except OSError: # handle error; you can also catch specific errors like # FileExistsError and so on. print(new_directory2) # prints "./python_dir/New_Folder/sub-directory" # unix, linux, macOS example # prints "C:\python_dir\New_Folder\sub-directory" # Window example
Code language: Python (python)

The fastest safest way to create new folders if not exists and skip if exists:

Source code Python 1:

from pathlib import Path Path("path/with/childs/…/").mkdir(parents=True, exist_ok=True)
Code language: Python (python)

Source code Python 2:

from pathlib import Path path = Path("/my/directory/filename.txt") try: if not path.parent.exists(): path.parent.mkdir(parents=True) except OSError: # handle error; you can also catch specific errors like # FileExistsError and so on.
Code language: Python (python)

Source code Python 3:

Python 3.5+:

import pathlib pathlib.Path('/my/directory').mkdir(parents=True, exist_ok=True)
Code language: PHP (php)

pathlib.Path.mkdir as used above recursively creates the folder and does not raise an exception if the folder already exists. If you don’t need or want the parents to be created, skip the parent’s argument.

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts