makedirs(name [, mode=0o777][, exist_ok=False]) Super-mkdir; create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. If the target directory already exists, raise a
(name, mode=0o777, exist_ok=False)
| 220 | # (Inspired by Eric Raymond; the doc strings are mostly his) |
| 221 | |
| 222 | def makedirs(name, mode=0o777, exist_ok=False): |
| 223 | """makedirs(name [, mode=0o777][, exist_ok=False]) |
| 224 | |
| 225 | Super-mkdir; create a leaf directory and all intermediate ones. Works like |
| 226 | mkdir, except that any intermediate path segment (not just the rightmost) |
| 227 | will be created if it does not exist. If the target directory already |
| 228 | exists, raise an OSError if exist_ok is False. Otherwise no exception is |
| 229 | raised. This is recursive. |
| 230 | |
| 231 | """ |
| 232 | head, tail = path.split(name) |
| 233 | if not tail: |
| 234 | head, tail = path.split(head) |
| 235 | if head and tail and not path.exists(head): |
| 236 | try: |
| 237 | makedirs(head, exist_ok=exist_ok) |
| 238 | except FileExistsError: |
| 239 | # Defeats race condition when another thread created the path |
| 240 | pass |
| 241 | cdir = curdir |
| 242 | if isinstance(tail, bytes): |
| 243 | cdir = bytes(curdir, 'ASCII') |
| 244 | if tail == cdir: # xxx/newdir/. exists if xxx/newdir exists |
| 245 | return |
| 246 | try: |
| 247 | mkdir(name, mode) |
| 248 | except OSError: |
| 249 | # Cannot rely on checking for EEXIST, since the operating system |
| 250 | # could give priority to other errors like EACCES or EROFS |
| 251 | if not exist_ok or not path.isdir(name): |
| 252 | raise |
| 253 | |
| 254 | def removedirs(name): |
| 255 | """removedirs(name) |