makedirs - recursive directory creation

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


os module:
* makedirs - recursive directory creation

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve