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.
Python os.makedirs() Function Syntax
Syntax: os.makedirs(path, mode = 0o777, exist_ok = False)
Parameter:
- path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
- mode (optional) : A Integer value representing mode of the newly created directory..If this parameter is omitted then the default value Oo777 is used.
- 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/w3wiki/Authors/ihritik
Suppose we want to create directory ‘ihritik’ but Directory ‘w3wiki’ and ‘Authors’ are unavailable in the path. Then os.makedirs() method will create all unavailable/missing directory in the specified path. ‘w3wiki’ 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 “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
Contact Us