Handling the case where a directory already exists is one of the most common stumbling blocks in Python file-system scripting. Whether you use os.mkdir, os.Here's the thing — makedirs, or pathlib. Path.mkdir, the interpreter raises a FileExistsError the moment the target path is already taken — and knowing how to make that operation idempotent is what separates a fragile script from a reliable one. This guide walks through exactly why the error happens, the three clean ways to prevent it, and the subtle edge cases (race conditions, broken symlinks, umask, and files squatting on your directory path) that most tutorials skip Nothing fancy..
What os.mkdir Actually Does When the Directory Exists
os.mkdir(path, mode=0o777) maps directly to the operating system's mkdir() system call. Its job is narrow: create one directory level, and fail loudly if it cannot Small thing, real impact..
Not the most exciting part, but easily the most useful.
import os
os.mkdir("output") # first run: works
os.mkdir("output") # second run: FileExistsError
The exception is not a bug. FileExistsError is a subclass of OSError, and it carries a precise errno:
import os, errno
try:
os.mkdir("output")
except FileExistsError as exc:
print(exc.errno == errno.EEXIST) # True
print(exc.
### Why the language refuses to silently ignore it
Python follows the *explicit is better than implicit* principle here. If `os.mkdir` quietly returned on an existing path, your code could believe it had created a fresh, empty directory with your chosen `mode` — when in reality it was pointing at a pre-existing folder full of someone else's data, possibly with completely different permissions. Creating a directory is a side effect with consequences: it changes permissions, ownership, and what other programs see. Failing loudly protects you from that class of silent logic error.
## Solution 1: `os.makedirs` with `exist_ok=True`
The most widely used fix is the `exist_ok` parameter on `os.makedirs`:
```python
import os
os.makedirs("output/reports/2026", exist_ok=True)
Two things happen at once here:
- Intermediate directories are created.
os.mkdirwould raiseFileNotFoundErrorifoutputoroutput/reportsdid not exist;os.makedirsbuilds the whole chain. - An existing target is tolerated. With
exist_ok=True,