Easily Create Directories in Python: mkdir vs makedirs

1. Introduction

By using Python, you can easily manage files and directories. In particular, creating directories is one of the most common tasks for organizing files, backing up, and automatically generating them. This guide provides a detailed explanation of how to create directories using the os module and the pathlib module. It also covers recursive directory creation and error handling, aiming to be clear for Python beginners.

2. Creating Directories Using os.mkdir()

Basic Usage

os.mkdir() is the basic way to create a single directory at the specified path. However, this function has a limitation: it raises an error if the parent directory does not exist. For example, the following code shows a simple directory creation method.
import os

# Specify the path of the directory to create
dir_path = './new_directory'

# Create the directory
os.mkdir(dir_path)
With this code, a directory is created at the specified path, but if a directory with the same name already exists, FileExistsError occurs. This is a point to be aware of in os.mkdir().

Error Handling

You can prevent errors by checking whether the directory already exists before creating it. The following code is an example of this.
import os

# Specify the path of the directory to create
dir_path = './new_directory'

# Check whether the directory exists
if not os.path.exists(dir_path):
    os.mkdir(dir_path)
else:
    print(f"The directory '{dir_path}' already exists.")
Using this method, you can avoid errors that occur when mistakenly trying to create a directory that already exists.
侍エンジニア塾

3. Recursive Directory Creation Using os.makedirs()

Recursive Directory Creation

os.makedirs() can be considered a superset of os.mkdir(). Because it can create multiple levels of directories at once, it can create intermediate directories even when the parent directory does not exist.
import os

# Path including intermediate directories
dir_path = './parent_directory/sub_directory'

# Create directories recursively
os.makedirs(dir_path)
In this example, parent_directory and its sub_directory are created at once. The fact that all directories can be created without error even when intermediate directories do not exist demonstrates its high convenience.

Error Handling Using exist_ok=True

os.makedirs() has the exist_ok option, allowing the process to continue without raising an error even if the directory already exists.
import os

dir_path = './parent_directory/sub_directory'

# Do not raise an error even if the directory already exists
os.makedirs(dir_path, exist_ok=True)
Using this method eliminates the need to check in advance whether a directory exists, simplifying error handling.

4. Creating Directories with the pathlib Module

Creating Directories Using Path Objects

pathlib module is a convenient module for performing filesystem path operations that is available in Python 3.4 and later. Path() objects improve code readability.
from pathlib import Path

# Specify the directory path
dir_path = Path('./new_directory')

# Create the directory
dir_path.mkdir()
The advantage of pathlib is that it allows object-oriented path manipulation, enhancing code intuitiveness.

Recursive Directory Creation and Error Handling

Even when using pathlib for recursive directory creation, it can be easily achieved by simply specifying an option.
from pathlib import Path

# Path including intermediate directories
dir_path = Path('./parent_directory/sub_directory')

# Create including intermediate directories
dir_path.mkdir(parents=True, exist_ok=True)
In this code, multiple levels of directories, including intermediate ones, are created at once, and no error occurs if the directories already exist.

5. Checking Directory Existence and Error Handling

Verifying whether a directory already exists is a fundamental part of error handling. os module and pathlib to check for a directory’s existence and safely perform directory operations.

Checking Method Using the os Module

import os

dir_path = './new_directory'

if os.path.exists(dir_path):
    print(f"Directory '{dir_path}' already exists.")
else:
    print(f"Directory '{dir_path}' does not exist.")

Checking Method Using pathlib

from pathlib import Path

dir_path = Path('./new_directory')

if dir_path.exists():
    print(f"Directory '{dir_path}' already exists.")
else:
    print(f"Directory '{dir_path}' does not exist.")

6. Summary

In this article, we provided a detailed explanation of various ways to create directories using Python. I learned the difference between os.mkdir() and os.makedirs(), including how to handle recursive directory creation and error handling. Furthermore, I discovered that by using pathlib, a newer standard module in Python, I can write code that is simpler and more readable. Choose the method that best fits your use case and perform efficient directory operations.
年収訴求