Create a Directory in Python: mkdir(), makedirs()

Modified: | Tags: Python, File

In Python, you can create new directories (folders) using the os.mkdir() and os.makedirs() functions.

While os.mkdir() creates a single directory, os.makedirs() is more convenient when you need to create a directory and all required parent directories at once.

All sample code in this article assumes that the os module has already been imported. The os module is included in the standard library and does not require additional installation.

import os

Create a directory with os.mkdir()

os.mkdir() creates a new directory.

Provide a path string for the new directory. See the following article for more information on manipulating path strings.

The path string may include or omit a trailing delimiter, such as a slash (/) for UNIX and macOS, or a backslash (\) for Windows.

If the specified directory already exists, a FileExistsError will be raised.

new_dir_path = 'data/temp/new-dir'

os.mkdir(new_dir_path)

# os.mkdir(new_dir_path)
# FileExistsError: [Errno 17] File exists: 'data/temp/new-dir/'

A FileNotFoundError will be raised if you attempt to create a new directory within a non-existent directory.

new_dir_path_recursive = 'data/temp/new-dir2/new-sub-dir'

# os.mkdir(new_dir_path_recursive)
# FileNotFoundError: [Errno 2] No such file or directory: 'data/temp/new-dir2/new-sub-dir'

When using os.mkdir(), ensure that all parent directories of the target directory already exist. To create new directories along with their parent directories, use os.makedirs() as explained in the next section.

Create nested directories with os.makedirs()

os.makedirs() creates all intermediate-level directories needed to reach the final target directory.

By default, if you specify an existing directory, a FileExistsError will be raised.

new_dir_path_recursive = 'data/temp/new-dir2/new-sub-dir'

os.makedirs(new_dir_path_recursive)

# os.makedirs(new_dir_path_recursive)
# FileExistsError: [Errno 17] File exists: 'data/temp/new-dir2/new-sub-dir'

The exist_ok argument (Python 3.2+)

The exist_ok argument was added to os.makedirs() in Python 3.2.

If you set exist_ok=True, specifying an existing directory will not raise an error. Note that the default value is exist_ok=False.

os.makedirs(new_dir_path_recursive, exist_ok=True)

In versions of Python prior to 3.2, the exist_ok argument is not available. In such cases, you can use a try block to handle exceptions or check if the target directory exists using os.path.isdir().

Handle exceptions with try:

try:
    os.makedirs(new_dir_path_recursive)
except FileExistsError:
    pass

Check for the existence of a directory with os.path.isdir():

def my_makedirs(path):
    if not os.path.isdir(path):
        os.makedirs(path)

my_makedirs(new_dir_path_recursive)

Related Categories

Related Articles