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

29,185

Solution 1

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

Solution 2

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.

Solution 3

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

Solution 4

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.

Share:
29,185
pynovice
Author by

pynovice

Copy Paste is not programming

Updated on May 03, 2020

Comments

  • pynovice
    pynovice about 4 years

    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.
    
  • Voo
    Voo about 11 years
    That's an inherent race condition 7and therefore a very bad idea.
  • Nicu Stiurca
    Nicu Stiurca about 11 years
    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 exception
  • pynovice
    pynovice about 11 years
    exc doesn't have errno attribute.
  • Trebor Rude
    Trebor Rude about 11 years
    That should be os.mkdirs (the ending s is important), but SO won't let me submit such a small edit.
  • WhyNotHugo
    WhyNotHugo about 10 years
    This does not do the same as "mkdir -p": -p, --parents: no error if existing, make parent directories as needed
  • Eduard Luca
    Eduard Luca about 10 years
    @Hugo edited the answer so that it now uses the makedirs function, thus working like mkdir -p
  • John Kugelman
    John Kugelman about 10 years
    Edited. exist_ok=True is much simpler than checking errno and ignoring certain exceptions.
  • Catskul
    Catskul almost 10 years
    rolled back to cover python 2.7
  • Jason S
    Jason S almost 10 years
    Shouldn't there be an else raise? An if statement with a pass body does nothing.
  • Connor
    Connor about 5 years
    Avoid running unnecessary shell commands if you don't have to