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. Ifexist_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=Truecreates intermediate directories,exist_ok=Trueavoids 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.mkdirto create nested directories will fail if parent folders don't exist. - Not handling
FileExistsErrorwhen the directory already exists. - Confusing
exist_okparameter inos.makedirsandpathlib.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:
| Method | Description | Key Parameters |
|---|---|---|
| os.mkdir(path) | Creates a single directory | No parameters for parents; errors if exists |
| os.makedirs(path, exist_ok=False) | Creates nested directories | exist_ok=True ignores if exists |
| pathlib.Path(path).mkdir(parents=False, exist_ok=False) | Object-oriented directory creation | parents=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.