Mkdir -p functionality in Python
To create directories with the mkdir -p
functionality in Python, use os.makedirs()
, setting exist_ok=True
will prevent 'Directory exists' errors.
Example:
Similarly, with Python 3.5 and above, you can use pathlib.Path.mkdir
- elegant and object-oriented!
Example:
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:
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:
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:
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:
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:
Durable Python scripts
Sometimes (rarely though), simple is better, and a single system call might just do the trick:
However, the safer choice is to stick with built-in Python functions.
Was this article helpful?