26

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
  • 7,424
  • 25
  • 69
  • 109

5 Answers5

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
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
22

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,484
  • 3
  • 27
  • 35
Michael Ma
  • 872
  • 8
  • 20
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
WhyNotHugo
  • 9,423
  • 6
  • 62
  • 70
singer
  • 2,616
  • 25
  • 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
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.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
-5

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

pitfall
  • 2,531
  • 1
  • 21
  • 21