makedirs - recursive directory creation
suggest changeGiven a local directory with the following contents:
└── dir1
├── subdir1
└── subdir2
We want to create the same subdir1, subdir2 under a new directory dir2, which does not exist yet.
import os
os.makedirs("./dir2/subdir1")
os.makedirs("./dir2/subdir2")
Running this results in
├── dir1
│ ├── subdir1
│ └── subdir2
└── dir2
├── subdir1
└── subdir2
dir2 is only created the first time it is needed, for subdir1’s creation.
If we had used os.mkdir instead, we would have had an exception because dir2 would not have existed yet.
os.mkdir("./dir2/subdir1")
OSError: [Errno 2] No such file or directory: './dir2/subdir1'
That text is the POSIX form. On Windows, Python 3.14.6 raises FileNotFoundError with errno 2 and WinError 3.
os.makedirs won’t like it if the target directory exists already. If we run it again:
OSError: [Errno 17] File exists: './dir2/subdir1'
That text is the POSIX form. On Windows the same call raises FileExistsError. errno is still 17, and the Windows error is WinError 183. exist_ok=True leaves an existing directory in place.
However, this could easily be fixed by catching the exception and checking that the directory has been created.
try:
os.makedirs("./dir2/subdir1")
except OSError:
if not os.path.isdir("./dir2/subdir1"):
raise
try:
os.makedirs("./dir2/subdir2")
except OSError:
if not os.path.isdir("./dir2/subdir2"):
raise