How to create a subdirectory with Python?
In this article we will learn how to create a subdirectory with Python, in a simple way using the language’s libs.

What’s up programmer, ok? Let’s learn more about Python!
For Python version 3.5+ we have a very easy way to solve this problem
Basically let’s call Path from lib pathlib
And use the mkdir method
See the example:
from pathlib import Path # creating the directory Path("dir").mkdir(parents=True, exist_ok=True) # creating the subdirectory Path("dir/subdir").mkdir(parents=True, exist_ok=True)
That way you will create the directory first, then the subdirectory
But if you already have the main directory, you can use only the second sentence and then the subdirectory will also be created
Note that when using only the second method, you need the parent directory to exist
Otherwise Python will generate an error in your program
This also ensures that we don’t create a parent directory by mistake, which can be very bad for the program.
And the good thing is that we do all this operation in one line
Python showing again its power and simplicity! 😀
Conclusion
In this article we learned how to create a subdirectory with Python
We use the Path that comes from the pathlib library
In it we have the mkdir method, which can create both directories and subdirectories
Do you want to learn more about Python? Click here!