← Back to Articles
Tutorial

How to Create a Directory in Python

Learn how to create directories in Python using os and pathlib modules with best practices and common mistakes to avoid.

Creating directories is a fundamental task in programming, allowing for structured data storage. Python provides simple methods to create directories using built-in modules.

Python's os and pathlib modules are commonly used to create directories. Using os, you can call os.mkdir() for single directories or os.makedirs() for nested ones. Pathlib's Path().mkdir() offers a modern approach, making your code more readable and concise.

To ensure your directory creation is efficient, check if a directory already exists to avoid errors. Use exception handling to manage any unexpected issues, and consider setting appropriate permissions for security.

A common mistake is not checking if a directory already exists before attempting to create it, which can lead to errors. Another pitfall is misunderstanding the difference between os.mkdir() and os.makedirs().

Code Examples

Example 1

import os

# Create a single directory
os.mkdir('new_directory')

Example 2

from pathlib import Path

# Create a directory using pathlib
Path('new_directory').mkdir(parents=True, exist_ok=True)

More Python Tutorials