In [1]:
import os
In [2]:
new_dir_path = 'data/temp/new-dir'
os.mkdir(new_dir_path)
In [3]:
# os.mkdir(new_dir_path)
# FileExistsError: [Errno 17] File exists: 'data/temp/new-dir/'
In [4]:
new_dir_path_recursive = 'data/temp/new-dir2/new-sub-dir'
# os.mkdir(new_dir_path_recursive)
# FileNotFoundError: [Errno 2] No such file or directory: 'data/temp/new-dir2/new-sub-dir'
In [5]:
new_dir_path_recursive = 'data/temp/new-dir2/new-sub-dir'
os.makedirs(new_dir_path_recursive)
In [6]:
# os.makedirs(new_dir_path_recursive)
# FileExistsError: [Errno 17] File exists: 'data/temp/new-dir2/new-sub-dir'
In [7]:
os.makedirs(new_dir_path_recursive, exist_ok=True)
In [8]:
try:
os.makedirs(new_dir_path_recursive)
except FileExistsError:
pass
In [9]:
def my_makedirs(path):
if not os.path.isdir(path):
os.makedirs(path)
In [10]:
my_makedirs(new_dir_path_recursive)