Python Language The os Module makedirs - recursive directory creation

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Given 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'

os.makedirs won't like it if the target directory exists already. If we re-run it again:

OSError: [Errno 17] File exists: './dir2/subdir1'

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


Got any Python Language Question?