Python
Programming
mkdir -p
File System
Python Libraries

mkdir -p functionality in Python

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

The mkdir -p command in Unix-based systems is a powerful functionality that allows the creation of nested directories. Python, through its standard library, provides a similar functionality that can be used in scripts and applications to create directories in a way that mimics the behavior of mkdir -p. This functionality is crucial when your program needs to ensure the existence of a directory path before proceeding with file operations.

Understanding Python's os.makedirs()

In Python, the equivalent of Unix's mkdir -p is implemented through the os.makedirs() function. This function is a part of the os module and is used to create directory trees; that is, it will create all intermediate-level directories needed to contain the leaf directory.

Syntax and Parameters

The function signature is:

python
os.makedirs(name, mode=0o777, exist_ok=False)
  • name: Path of the directory to be created.
  • mode: The mode of the directory. By default, it is set to 0o777.
  • exist_ok: A Boolean which defaults to False. If True, FileExistsError will not be thrown if the directory already exists.

How It Works

If exist_ok is set to False (the default setting), the function will throw a FileExistsError if the directory to be created already exists. By setting exist_ok to True, this error is suppressed, mimicking the behavior of mkdir -p.

Example Usage

Here's a simple script demonstrating the use of os.makedirs():

python
1import os
2
3# Creating a nested directory path
4path = "/tmp/a/b/c"
5
6try:
7   os.makedirs(path, exist_ok=True)
8   print(f"Directory {path} created successfully")
9except OSError as error:
10   print(f"Error creating directory {path}: {error}")

In this example, os.makedirs() will create the directories /tmp/a, /tmp/a/b, and /tmp/a/b/c. If any or all of these directories already exist and exist_ok=True, no error will be raised.

Comparison with os.mkdir()

It's important to distinguish os.makedirs() from os.mkdir(). The latter is used to create a single directory and will raise an OSError if the directory already exists or if the parent directory does not exist. In contrast, os.makedirs() handles both the creation of nested directories and the case where directories might already exist (with exist_ok=True).

Enhancing Functionality with pathlib

Python's pathlib module, introduced in Python 3.4, provides an object-oriented approach to handling filesystem paths. The Path class in pathlib has a method mkdir() which is similar to os.makedirs() but part of a more intuitive and flexible API.

Example with pathlib.Path

python
1from pathlib import Path
2
3# Creating a nested directory path using pathlib
4path = Path("/tmp/a/b/c")
5path.mkdir(parents=True, exist_ok=True)

This code does the same as the previous os.makedirs() example but uses pathlib.Path.mkdir() with parents=True to ensure that parent directories are created.

Summary Table

Here's a table summarizing the key points covered:

Feature/FunctionDescriptionUse Case
os.makedirs()Creates nested directories, handling intermediate directories.When you need to ensure the entire path exists.
exist_ok parameterSuppresses FileExistsError if set to True.Useful when the existence of directories is uncertain.
pathlib.Path.mkdir()Method of Path class in pathlib for directory creation.Provides a more intuitive and object-oriented approach.

Conclusion

Creating directory trees in Python can be easily accomplished using os.makedirs() or pathlib.Path.mkdir(), with functionality similar to Unix's mkdir -p. Whether you're working on a script that handles file outputs or setting up directory structures for application data, these functions provide a robust way to manage directories in Python.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.