To create directories or folders in python, depends on how you call it, use the mkdir function of os.
This function can throw an exception so it should normally be used within a try statement.
import os # geekole.com # The name of the folder or directory to be created is defined directory = "/home/geekole/Documents/python/files/test_dir" try: os.mkdir(directory) except OSError: print("The creation of the directory %s failed" % directory) else: print("Directory has been created: %s " % directory)
In our case the “test_dir” folder does not exist, when executing the code it is created without problems.
If we run the code a second time, with the already existing folder, an error would be generated.
“The creation of the directory /home… /files/test_dir failed”
We hope this example of how to create directories or folders in python will be useful to you.
Note: The examples are edited and run with the help of Visual Studio Code.