The Wayback Machine - https://web.archive.org/web/20241005213512/https://www.geeksforgeeks.org/python-os-makedirs-method/
Open In App

Python | os.makedirs() method

Last Updated : 15 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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


Previous Article
Next Article

Similar Reads

Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Difference between Method Overloading and Method Overriding in Python
Method Overloading: Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading.Note: Python does not support
3 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that
5 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
What is the Proper Way to Call a Parent's Class Method Inside a Class Method?
In object-oriented programming, calling a parent class method inside a class method is a common practice, especially when you want to extend or modify the functionality of an inherited method. This process is known as method overriding. Here's how to properly call a parent class method inside a class method in Python. Basic Syntax Using super()The
3 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Python | os._exit() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buff
2 min read
Python | os.WEXITSTATUS() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.WEXITSTATUS() method in Python is used to get the integer parameter used by a process in exit(2) system call if os.WIFEXITED(sta
3 min read
Python | os.abort() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.abort() method in Python is used to generate a SIGABRT signal to the current process. On Unix, this method produces a core dump
2 min read
Python | os.renames() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.renames() method is a recursive directory or file renaming function. It works like os.rename() method except creation of any int
2 min read
Python | os.lseek() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.lseek() method sets the current position of file descriptor fd to the given position pos which is modified by how. Syntax: os.ls
3 min read
Python calendar module : formatmonth() method
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. class calendar.TextCalendar(firstweekday=0) can be used to generate plain text
2 min read
Python | PyTorch sin() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.sin() provides support for the sine function in PyTorch. It expects the input in radian form and the output is in the range [-1, 1]. The input type is tensor and if the input conta
2 min read
Python | Sympy Line.is_parallel() method
In Sympy, the function is_parallel() is used to check whether the two linear entities are parallel or not. Syntax: Line.is_parallel(l2) Parameters: l1: LinearEntity l2: LinearEntity Returns: True: if l1 and l2 are parallel, False: otherwise. Example #1: # import sympy and Point, Line from sympy import Point, Line p1, p2 = Point(0, 0), Point(1, 1) p
1 min read
Python PIL | GaussianBlur() method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method. PIL.ImageFilter.GaussianBlur() method create Gaussian blur filter. Syntax: PIL.ImageFilter.GaussianBlur(radius=5) Par
1 min read
Python range() Method
There are many iterables in Python like list, tuple etc. range() gives another way to initialize a sequence of numbers using some conditions.range() is commonly used in for looping hence, knowledge of same is key aspect when dealing with any kind of Python code. Syntax : range(start, stop, step)Parameters : start : Element from which sequence const
3 min read
Python String casefold() Method
Python String casefold() method is used to convert string to lowercase. It is similar to the Python lower() string method, but the case removes all the case distinctions present in a string. Python String casefold() Method Syntax Syntax: string.casefold() Parameters: The casefold() method doesn't take any parameters. Return value: Returns the case
1 min read
Python String isspace() Method
Python String isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters, such as: ‘ ‘ – Space‘\t’ – Horizontal tab‘\n’ – Newline‘\v’ – Vertical tab‘\f’ – Feed‘\r’ – Carriage returnPython String isspace()
2 min read
Python String isalpha() Method
Python String isalpha() method is used to check whether all characters in the String are an alphabet. Python String isalpha() Method SyntaxSyntax: string.isalpha() Parameters: isalpha() does not take any parameters Returns: True: If all characters in the string are alphabet.False: If the string contains 1 or more non-alphabets.Errors and Exceptions
4 min read
Python String isprintable() Method
Python String isprintable() is a built-in method used for string handling. The isprintable() method returns "True" if all characters in the string are printable or the string is empty, Otherwise, It returns "False". This function is used to check if the argument contains any printable characters such as: Digits ( 0123456789 )Uppercase letters ( ABC
3 min read
Python String isdigit() Method
Python String isdigit() method returns “True” if all characters in the string are digits, Otherwise, It returns “False”. Python String isdigit() Method Syntax Syntax: string.isdigit() Parameters: isdigit() does not take any parameters Returns: True - If all characters in the string are digits.False - If the string contains 1 or more non-digits. Tim
3 min read
Python String isnumeric() Method
The isnumeric() method is a built-in method in Python that belongs to the string class. It is used to determine whether the string consists of numeric characters or not. It returns a Boolean value. If all characters in the string are numeric and it is not empty, it returns “True” If all characters in the string are numeric characters, otherwise ret
3 min read
Python | Numpy np.hermefit() method
With the help of np.hermefit() method, we can get the least square fit of hermite series by using np.hermefit() method. Syntax : np.hermefit(x, y, deg) Return : Return the least square fit of given data. Example #1 : In this example we can see that by using np.hermefit() method, we are able to get the least square fit of hermite series by using thi
1 min read
Python | Numpy np.hermevander() method
With the help of np.hermevander() method, we can get the pseudo vandermonde matrix at a given degree by using np.hermevander() method. Syntax : np.hermevander(x, deg) Return : Return the pseudo vandermonde matrix. Example #1 : In this example we can see that by using np.hermevander() method, we are able to get the pseudo vandermonde matrix at a giv
1 min read
Python groupby method to remove all consecutive duplicates
Given a string S, remove all the consecutive duplicates. Examples: Input : aaaaabbbbbb Output : ab Input : geeksforgeeks Output : geksforgeks Input : aabccba Output : abcba We have existing solution for this problem please refer Remove all consecutive duplicates from the string link. We can solve this problem in python quickly using itertools.group
2 min read
Python Set clear() Method
Python Set clear() method removes all elements from the set. Python Set clear() Method Syntax: Syntax: set.clear() parameters: The clear() method doesn't take any parameters. Return: None Time complexity : The time complexity of set.clear() function on a set with n element is O(n) . Example 1: Python Set clear() Method Example C/C++ Code test_set =
2 min read
Python Set isdisjoint() Method
Python set isdisjoint() function check whether the two sets are disjoint or not, if it is disjoint then it returns True otherwise it will return False. Two sets are said to be disjoint when their intersection is null. Python set isdisjoint() Method Syntax: Syntax: set1.isdisjoint(set2) Parameters: another set to compare withoran iterable (list, tup
2 min read
Python Set pop() Method
Python set pop() removes any random element from the set and returns the removed element. In this article, we will see about the Python set pop() method. Example Input: {9, 1, 0} Output: {9, 1} Explanation: By using set pop() method, a random element 0 is removed from the set and remaining set is returned.Python Set pop() SyntaxSyntax: set_obj.pop(
2 min read
Practice Tags :