0
0
PythonHow-ToBeginner · 3 min read

How to Create Directory in Python: Simple Guide

To create a directory in Python, use os.mkdir(path) for a single directory or os.makedirs(path) for nested directories. Alternatively, use pathlib.Path(path).mkdir() for an object-oriented approach.
📐

Syntax

Python provides two main ways to create directories: using the os module and the pathlib module.

  • os.mkdir(path): Creates a single directory at the specified path. Throws an error if the directory already exists.
  • os.makedirs(path, exist_ok=False): Creates all intermediate directories in the path. If exist_ok=True, it won't raise an error if the directory exists.
  • pathlib.Path(path).mkdir(parents=False, exist_ok=False): Object-oriented way to create directories. parents=True creates intermediate directories, exist_ok=True avoids errors if directory exists.
python
import os
from pathlib import Path

# Using os module
os.mkdir('folder')  # create single directory
os.makedirs('parent/child', exist_ok=True)  # create nested directories

# Using pathlib module
Path('folder_path').mkdir(parents=True, exist_ok=True)
💻

Example

This example shows how to create a single directory and nested directories safely using both os and pathlib. It also handles the case when the directory already exists.

python
import os
from pathlib import Path

# Create a single directory using os.mkdir
try:
    os.mkdir('my_folder')
    print('Directory my_folder created')
except FileExistsError:
    print('Directory my_folder already exists')

# Create nested directories using os.makedirs
os.makedirs('parent_folder/child_folder', exist_ok=True)
print('Nested directories created or already exist')

# Create directory using pathlib
path = Path('pathlib_folder')
path.mkdir(exist_ok=True)
print('Directory pathlib_folder created or already exists')
Output
Directory my_folder created Nested directories created or already exist Directory pathlib_folder created or already exists
⚠️

Common Pitfalls

Common mistakes when creating directories include:

  • Using os.mkdir to create nested directories will fail if parent folders don't exist.
  • Not handling FileExistsError when the directory already exists.
  • Confusing exist_ok parameter in os.makedirs and pathlib.Path.mkdir.

Always use os.makedirs or pathlib.Path.mkdir with exist_ok=True to avoid errors if the directory exists.

python
import os

# Wrong: os.mkdir fails if parent folder missing
try:
    os.mkdir('parent/child')
except FileNotFoundError as e:
    print('Error:', e)

# Right: os.makedirs creates all needed folders
os.makedirs('parent/child', exist_ok=True)
print('Nested directories created')
Output
Error: [Errno 2] No such file or directory: 'parent/child' Nested directories created
📊

Quick Reference

Summary of directory creation methods:

MethodDescriptionKey Parameters
os.mkdir(path)Creates a single directoryNo parameters for parents; errors if exists
os.makedirs(path, exist_ok=False)Creates nested directoriesexist_ok=True ignores if exists
pathlib.Path(path).mkdir(parents=False, exist_ok=False)Object-oriented directory creationparents=True for nested; exist_ok=True to ignore existing

Key Takeaways

Use os.makedirs or pathlib.Path.mkdir with exist_ok=True to safely create directories without errors.
os.mkdir only creates one directory and fails if parent folders don't exist.
Handle FileExistsError to avoid crashes when directory already exists.
pathlib offers a modern, readable way to work with directories.
Always check or handle exceptions when creating directories to make your code robust.