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

I want to run the mkdir command as:

 mkdir -p directory_name 

What is the way to do this in Python?

 os.mkdir(directory_name [, -p]) didn't work for me. 
+14
python mkdir
source share
5 answers

You can try the following:

 # 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 
+26
source share

Something like that:

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

UPD: as said in the comments, you need to check for thread safety exception

 try: os.makedirs(directory_name) except OSError as err: if err.errno!=17: raise 
+12
source share

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

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

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

+9
source share

If you use 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) 

parent parents=True creates parent directories as needed

exist_ok=True says mkdir() does not exist_ok=True if the directory already exists

See pathlib.Path.mkdir() docs .

+1
source share

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

-3
source share

All Articles