Python os.makedirs() Function Examples
Below are some examples of os.makedirs() function by which we can see how to create directories recursively using the os module:
Creating Directory Using os.makedirs()
In this example, the os.makedirs()
method is utilized to create nested directories. The first section creates a directory named “ihritik” within the “Authors” directory path. The second section, with specified permissions, creates a directory “c” nested within “w3wiki/a/b”.
Python3
import os # Leaf directory directory = "ihritik" # Parent Directories parent_dir = "/home/User/Documents/w3wiki/Authors" # Path path = os.path.join(parent_dir, directory) # Create the directory 'ihritik' os.makedirs(path) print ( "Directory '%s' created" % directory) # Leaf directory directory = "c" # Parent Directories parent_dir = "/home/User/Documents/w3wiki/a/b" # mode mode = 0o666 path = os.path.join(parent_dir, directory) os.makedirs(path, mode) print ( "Directory '%s' created" % directory) |
Output:
Directory 'ihritik' created
Directory 'c' created
Errors while using os.makedirs() method
In this example, the os.makedirs()
method attempts to create a directory named “ihritik” within the “w3wiki” path. If the directory already exists, the method raises an OSError
. Upon successful creation, a confirmation message is printed.
Python3
import os # Directory directory = "ihritik" # Parent Directory path parent_dir = "/home/User/Documents/w3wiki" # Path path = os.path.join(parent_dir, directory) # Create the directory 'ihritik' os.makedirs(path) print ( "Directory '%s' created" % directory) |
Output:
Traceback (most recent call last):
File "makedirs.py", line 21, in
os.makedirs(path)
File "/usr/lib/python3.6/os.py", line 220, in makedirs
mkdir(name, mode)
FileExistsError: [Errno 17] File exists: '/home/User/Documents/w3wiki/ihritik'
Handling errors while using os.makedirs() method
In this example, the os.makedirs()
method is used with the exist_ok
parameter set to True
to suppress OSError
if the directory already exists. If the directory doesn’t exist, it will be created. However, other OSError
exceptions, such as an invalid path name, can still be raised and need to be handled separately.
Python3
import os # Directory directory = "ihritik" # Parent Directory path parent_dir = "/home/ihritik/Desktop/w3wiki" # Path path = os.path.join(parent_dir, directory) # Create the directory 'ihritik' try : os.makedirs(path, exist_ok = True ) print ( "Directory '%s' created successfully" % directory) except OSError as error: print ( "Directory '%s' can not be created" ) |
Output:
Directory 'ihritik' created successfully
Python | os.makedirs() method
All functions in the os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system. In this article, we will see how to create directories recursively using the os module and also about os.makedirs() method.