Create & Delete Folders in Python: Using os vs. pathlib

1. Basic Method for Creating Folders in Python

Python provides a simple way to create folders using the standard library. The most commonly used is the os module. This section explains in detail how to create folders using the os module.

How to Create Folders in Python: os Module

os module allows you to create folders within your program. This is useful for organizing data or creating directories to store logs, among other cases. The basic method for creating a folder is as follows.
import os
# Specify the path of the folder to create
path = 'example_folder'
# Create the folder
os.mkdir(path)
In this code, the os.mkdir() function is used to create a new folder named “example_folder”. However, this function raises a FileExistsError if the folder already exists.

Creating Multi-level Folders: os.makedirs()

If you want to create not only a single folder but also multiple levels of directories at once, use the os.makedirs() function.
import os
# Specify a multi-level folder path
path = 'example_folder/subfolder'
# Create the folder even if the parent directory does not exist
os.makedirs(path)
In this way, using os.makedirs() you can also create any missing parent directories in the specified path simultaneously. This provides the convenience of creating an entire folder structure at once.

Error Handling: Using exist_ok=True

If you want to continue processing without raising an error when the folder already exists, use the exist_ok=True option. Setting it as shown in the example below prevents an error even if the folder exists.
import os
path = 'example_folder/subfolder'
# Ignore the error even if the folder already exists
os.makedirs(path, exist_ok=True)
This allows you to write robust code that doesn’t error out when the program attempts to create the same folder each time it runs.

2. Creating Folders Using the Pathlib Module

Python 3.4 and later added the pathlib module to the standard library. This module allows object‑oriented path manipulation and makes folder creation intuitive. Here we explain how to create folders using the pathlib module.

How to Use the Pathlib Module

pathlib.Path() can be used to create directories. Like the os module, specifying exist_ok=True avoids errors when the folder already exists.
from pathlib import Path
# Specify the path of the folder you want to create
path = Path('example_folder/subfolder')
# Create the folder
path.mkdir(parents=True, exist_ok=True)
In this code, setting parents=True creates any missing parent directories as well. This replicates the behavior of os.makedirs().

Advantages of the Pathlib Module

A major feature of the pathlib module is that it supports object‑oriented operations. Using a Path object lets you not only create folders but also combine paths and manipulate files intuitively. This improves code readability and maintainability.

3. Error Handling When Creating Folders

When creating folders, various errors can occur. For example, insufficient permissions or an invalid specified path. This section explains how to implement error handling.

Handling Permission Errors and Invalid Paths

os.makedirs() and pathlib.Path().mkdir() can raise common errors such as PermissionError and FileNotFoundError. Properly handling these errors lets you build more robust programs. Below is an example of error handling.
import os
path = 'example_folder/subfolder'
try:
    os.makedirs(path, exist_ok=True)
    print(f'Folder "{path}" has been created.')
except PermissionError:
    print("You don't have permission to create the folder.")
except FileNotFoundError:
    print('The specified path is invalid.')
except Exception as e:
    print(f'An unexpected error occurred: {e}')
This code shows how to address each common error and also handles unexpected errors. As a result, the program continues without interruption and errors are processed appropriately.

Advanced Error Handling

When folder creation might fail, consider logging the error details or notifying the user. In large‑scale applications, error handling has a big impact on user experience, so thorough handling is required.

4. How to Delete a Folder

In addition to creating folders, you often need to delete folders you no longer need. In Python, you can use the standard library os module or shutil module to delete folders. Here, we’ll explain the specific methods.

Folder Deletion Using os.rmdir()

os module has a function called rmdir() that can delete a folder. However, this function requires the folder to be empty.
import os
# Specify the path of the folder to delete
path = 'example_folder/subfolder'
# Delete the folder
os.rmdir(path)
This code works correctly only when the specified folder is empty. If there are files or other directories inside the folder, an OSError occurs.

Recursive Folder Deletion Using shutil.rmtree()

If there are files or other subfolders inside a folder, you can use the shutil module’s rmtree() function to recursively delete the folder and its contents.
import shutil
# Specify the path of the folder to delete
path = 'example_folder/subfolder'
# Delete the folder and its contents
shutil.rmtree(path)
This method can delete folders even when they are not empty, making it convenient for removing an entire directory tree. However, because deleted files and folders cannot be recovered, you need to handle it carefully.

Error Handling

Error handling is also important when deleting folders. For example, errors occur if you lack permission for the folder you’re deleting or if the specified path is invalid. Below is a code example that includes error handling.
import shutil
path = 'example_folder/subfolder'
try:
    shutil.rmtree(path)
    print(f'Folder "{path}" has been deleted.')
except PermissionError:
    print('You don\'t have permission to delete the folder.')
except FileNotFoundError:
    print('The specified folder was not found.')
except Exception as e:
    print(f'An unexpected error occurred: {e}')
This code handles errors that occur during deletion and also flexibly deals with unexpected errors.
侍エンジニア塾

5. Real-World Use Cases

Here we present practical use cases that combine folder creation and deletion, useful for real projects and data processing. In particular, we consider scenarios such as organizing annual or monthly data into separate folders.

Creating Folders by Year and Month

For example, if you want to organize data by year or month, you can create a script that automatically generates the folders.
import os
from datetime import datetime
# Get the current year and month
current_year = datetime.now().year
current_month = datetime.now().month
# Set the folder path
folder_path = f'data/{current_year}/{current_month}'
# Create the folder
os.makedirs(folder_path, exist_ok=True)
print(f'Folder "{folder_path}" has been created.')
This script automatically creates folders based on the current year and month, helping you organize data efficiently.

Bulk Deletion of Folders

If you need to delete unnecessary folders in bulk based on specific criteria, you can efficiently handle this with Python. For instance, you can create a script that removes old data folders that have existed for longer than a certain period.
import shutil
import os
from datetime import datetime, timedelta
# Get the date 30 days ago
threshold_date = datetime.now() - timedelta(days=30)
# Base path for folders to delete
base_path = 'data/'
# Check folders and delete old ones
for folder_name in os.listdir(base_path):
    folder_path = os.path.join(base_path, folder_name)
    if os.path.isdir(folder_path):
        folder_date = datetime.strptime(folder_name, '%Y-%m-%d')
        if folder_date < threshold_date:
            shutil.rmtree(folder_path)
            print(f'Old folder "{folder_path}" has been deleted.')
In these use cases, automating folder management and organization with a program eliminates the need for manual operations.

6. Summary

This article explained how to create and delete folders using Python. From basic operations using the os module and the pathlib module to error handling when creating folders and real-world application cases, a wide range was introduced. By leveraging this knowledge, you can create programs that efficiently manage data and files. As a next step, in addition to creating and deleting folders, it is recommended to learn techniques related to more advanced data management such as file operations and compression.