21

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.
pynovice
  • 6,802
  • 23
  • 67
  • 104

5 Answers5

32

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
Adem Öztaş
  • 18,635
  • 4
  • 32
  • 41
21

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.

Victor Häggqvist
  • 4,482
  • 3
  • 26
  • 35
Michael Ma
  • 832
  • 8
  • 20
12

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
WhyNotHugo
  • 8,964
  • 6
  • 59
  • 67
singer
  • 2,546
  • 23
  • 21
  • 2
    That's an inherent race condition 7and therefore a *very* bad idea. – Voo Apr 16 '13 at 06:10
  • 3
    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 – Nicu Stiurca Apr 16 '13 at 06:10
8

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.

Boris Verkhovskiy
  • 10,733
  • 7
  • 77
  • 79
-5

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

pitfall
  • 2,391
  • 19
  • 21