Python, how to create a directory
By Flavio Copes
Learn how to create a directory in Python with the os.mkdir() method, and how to wrap it in a try block to gracefully handle the OSError it can raise.
To create a directory in Python, use the os.mkdir() method provided by the os standard library module:
import os
dirname = '/Users/flavio/test'
os.mkdir(dirname)
If the call succeeds, the folder is there. If something goes wrong, Python raises an OSError exception. This happens when the directory already exists, when you don’t have write permissions on the parent folder, or when the disk is full.
We can wrap the call in a try block to catch the error and handle the problem by printing an error message:
import os
dirname = '/Users/flavio/test'
try:
os.mkdir(dirname)
except OSError:
print('Failed creating the directory')
else:
print('Directory created')
The else branch runs only when no exception was raised.
Catch the right exception
Catching a bare OSError hides the reason behind a generic message. A missing permission and an already existing folder look the same.
Python gives us more specific subclasses. FileExistsError is raised when the directory is already there:
try:
os.mkdir(dirname)
except FileExistsError:
print('Directory already exists')
An existing directory is often not a problem at all. In that case you can just pass, and let any other OSError propagate so you actually see what went wrong.
What if the parent folder is missing?
os.mkdir() creates one directory. If any intermediate folder in the path does not exist, it raises FileNotFoundError:
os.mkdir('/Users/flavio/projects/blog/drafts')
#FileNotFoundError if /Users/flavio/projects/blog is missing
To create the whole tree in one call, use os.makedirs():
os.makedirs('/Users/flavio/projects/blog/drafts')
It creates every missing folder along the way, like mkdir -p does in the terminal.
os.makedirs() also accepts an exist_ok parameter. Set it to True and the call won’t complain if the directory is already there:
os.makedirs(dirname, exist_ok=True)
This is my go-to line when a script needs a folder and I don’t care if it already exists. Run it once or a hundred times, the result is the same.
Related posts about python: