Open In App

Python | os.makedirs() method

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Python os.makedirs() Function Syntax

Syntax: os.makedirs(path, mode = 0o777, exist_ok = False) 

Parameter: 

  1. path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
  2. mode (optional) : A Integer value representing mode of the newly created directory..If this parameter is omitted then the default value Oo777 is used.
  3. exist_ok (optional) : A default value False is used for this parameter. If the target directory already exists an OSError is raised if its value is False otherwise not. For value True leaves directory unaltered. 

Return Type: This method does not return any value.

os.makedirs() Method in Python

os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all.

For example, consider the following path:

/home/User/Documents/GeeksForGeeks/Authors/ihritik

Suppose we want to create directory ‘ihritik’ but Directory ‘GeeksForGeeks’ and ‘Authors’ are unavailable in the path. Then os.makedirs() method will create all unavailable/missing directory in the specified path. ‘GeeksForGeeks’ and ‘Authors’ will be created first then ‘ihritik’ directory will be created.

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 “GeeksforGeeks/a/b”.

Python3




import os
 
# Leaf directory
directory = "ihritik"
 
# Parent Directories
parent_dir = "/home/User/Documents/GeeksForGeeks/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/GeeksforGeeks/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 “GeeksForGeeks” 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/GeeksForGeeks"
 
# 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/GeeksForGeeks/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/GeeksForGeeks"
 
# 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


Last Updated : 15 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads