How to run os.mkdir() with -p option in Python?
Asked Answered
T

5

29

I want to run mkdir command as:

mkdir -p directory_name

What's the method to do that in Python?

os.mkdir(directory_name [, -p]) didn't work for me.
Torquay answered 16/4, 2013 at 6:5 Comment(3)
Try os.makedirs('/multiple/path/')Dinky
duplicate: #600768Fourcycle
Possible duplicate of mkdir -p functionality in PythonSlipslop
S
33

You can try this:

# top of the file
import os
import errno

# the actual code
try:
    os.makedirs(directory_name)
except OSError as exc: 
    if exc.errno == errno.EEXIST and os.path.isdir(directory_name):
        pass
Silberman answered 16/4, 2013 at 6:8 Comment(7)
exc doesn't have errno attribute.Torquay
That should be os.mkdirs (the ending s is important), but SO won't let me submit such a small edit.Rifling
This does not do the same as "mkdir -p": -p, --parents: no error if existing, make parent directories as neededBuckshot
@Hugo edited the answer so that it now uses the makedirs function, thus working like mkdir -pTatyanatau
Edited. exist_ok=True is much simpler than checking errno and ignoring certain exceptions.Upanishad
rolled back to cover python 2.7Kuwait
Shouldn't there be an else raise? An if statement with a pass body does nothing.Fennec
D
24

According to the documentation, you can now use this since python 3.2

os.makedirs("/directory/to/make", exist_ok=True)

and it will not throw an error when the directory exists.

Dainedainty answered 22/3, 2018 at 3:19 Comment(1)
This also creates missing parents. Nice!Navaho
B
13

Something like this:

if not os.path.exists(directory_name):
    os.makedirs(directory_name)

UPD: as it is said in a comments you need to check for exception for thread safety

try:
    os.makedirs(directory_name)
except OSError as err:
    if err.errno!=17:
        raise
Biofeedback answered 16/4, 2013 at 6:9 Comment(2)
That's an inherent race condition 7and therefore a very bad idea.A1
this is prone to race conditions. Ie, if some other process/thread creates directory_name after the if but before the os.mkdirs, this code will throw exceptionFourcycle
M
11

If you're using pathlib, use Path.mkdir(parents=True, exist_ok=True)

from pathlib import Path

new_directory = Path('./some/nested/directory')
new_directory.mkdir(parents=True, exist_ok=True)

parents=True creates parent directories as needed

exist_ok=True tells mkdir() to not error if the directory already exists

See the pathlib.Path.mkdir() docs.

Matteroffact answered 30/9, 2018 at 20:41 Comment(0)
A
-5

how about this os.system('mkdir -p %s' % directory_name )

Aversion answered 21/7, 2017 at 3:54 Comment(1)
Avoid running unnecessary shell commands if you don't have toStubby

© 2022 - 2024 — McMap. All rights reserved.