Explain Codes LogoExplain Codes Logo

Mkdir -p functionality in Python

python
pathlib
mkdir
file-system
Alex KataevbyAlex Kataev·Dec 23, 2024
TLDR

To create directories with the mkdir -p functionality in Python, use os.makedirs(), setting exist_ok=True will prevent 'Directory exists' errors.

Example:

import os # Heading into the mountains to create a secret lair... I mean, directory os.makedirs('path/to/secret-lair', exist_ok=True)

Similarly, with Python 3.5 and above, you can use pathlib.Path.mkdir - elegant and object-oriented!

Example:

from pathlib import Path # A castle in the clouds? No problem! Path('path/to/cloud-castle').mkdir(parents=True, exist_ok=True)

Now, keep scrolling for a deeper understanding and best practices!

Creating Directories: The Pythonic Way

The cool kids use pathlib

With Python 3.5 came pathlib, letting us use filesystem paths as objects:

from pathlib import Path # Hello, new neighborhood! new_path = Path("/new/neighborhood") new_path.mkdir(parents=True, exist_ok=True)

Just like a mkdir -p, this handles missing parents and existing directories!

When Python was a toddler (older than 3.2)

Before Python 3.2, there was no exist_ok. So, we had to check if the directory exists and then make it:

# When we had to walk uphill both ways if not os.path.exists(directory): os.makedirs(directory)

Beware! In a multithreaded world, a race condition might occur - always try, catch!

Knock-knock, do I have permission?

Folders are like houses - need the right permissions! Always set the correct mode when making directories:

# Making a directory that's accessible by all, no secret stuff here os.makedirs('path/to/create', mode=0o770, exist_ok=True) # permission set to rwxrwx---

System calls? More like system stalls

Replacing multiple system calls with Python functionality? Cleaner code, better performance, and safer systems! So, stick with os.makedirs or pathlib.Path.mkdir.

Handling exceptions: because life happens

Work with files, work with exceptions! Always be ready for surprises and use proactive error handling:

try: os.makedirs('/some/path') except OSError as e: if e.errno != errno.EEXIST: raise # Oops, I did it again... Raised an exception, I mean! # Handle existing directory warnings

Not every path is a directory

Use os.path.isdir() to make sure a path is indeed a directory. Alternatively, os.path.exists() to check for file:

# Fact-checking: Is it really a directory? if os.path.isdir('/some/path'): print("Yep, it's a directory!") # Not FAKE news! else: os.makedirs('/some/path') # If not, we MAKE it!

Durable Python scripts

Sometimes (rarely though), simple is better, and a single system call might just do the trick:

import subprocess # Sometimes, you gotta do the manual labor subprocess.run(['mkdir', '-p', 'new/directory'])

However, the safer choice is to stick with built-in Python functions.