Python os.makedirs() Method
os.makedirs() Overview
The os.makedirs() method is used to recursively create multi-level directories.
If a subdirectory fails to be created or already exists, an OSError exception is thrown, Error 183 on Windows is an exception error that the directory already exists.
If the first argument path has only one level, i.e. only one level of directories are created, it is the same as the mkdir() function.
os.makedirs() Syntax
The syntax format of the makedirs() method is as follows.
os.makedirs(name, mode=511, exist_ok=False)
os.makedirs() Parameters
- path – The directory to be created recursively, either relative or absolute path.
- mode – Permission mode, the default mode is 511 (octal).
- exist_ok – Whether to trigger an exception when the directory exists.
- If exist_ok is False (the default), then a FileExistsError exception is raised if the target directory already exists.
- If exist_ok is True, the FileExistsError exception will not be raised if the target directory already exists.
os.makedirs() Return Value
This method has no return value.
os.makedirs() Demo#1
The following example demonstrates the use of the makedirs() method.
#!/usr/bin/python3
import os, sys
# Created directories
path = "/root/aaa/bbb/ccc"
os.makedirs( path, 0o777 );
print ("Paths are created!!!")
Output:
os.makedirs() Demo#2
By setting exist_ok as False error caused due already existing directory.
# Python program to explain os.makedirs() method
# importing os module
import os
# os.makedirs() method will raise
# an OSError if the directory
# to be created already exists
# But It can be suppressed by
# setting the value of a parameter
# exist_ok as True
# Directory
directory = "aaa"
# Parent Directory path
parent_dir = "/root"
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'aaa'
try:
os.makedirs(path, exist_ok = False)
print("Directory '%s' created successfully" %directory)
except OSError as error:
print("Directory '%s' can not be created" % path)
Output: