Python makedirs – os.makedirs() Method

In this tutorial, we’ll see how to use os.makedirs() method, as well as their errors while using this user face with a complete guide using a simple piece of code.

Introduction to os module

In Python, the OS module has methods for dealing with the operating system. Python’s basic utility modules include OS. This module provides a portable way of using operating system-dependent functionality.  Many functions to interface with the file system are includes in the os and os.path modules. Invalid or inaccessible file names and paths, or other parameters that have the right type but are not recognize by the operating system, all methods in the os module raise OSError.

In the OS module, there are several techniques for creating a directory. The following are

  • os.mkdir()
  • os.makedirs()

But in this article, we will only cover os.makedirs() method.

Overview and Syntax – os.makedirs()

In Python, the os.makedirs() function is use to recursively construct a directory. That is, if any intermediate-level directories are missing while creating the leaf directory, the os.makedirs() function will construct them all.

For example consider the following path:

/home/User/Documents/Softhunt/Authors/ranjeet

Let’s say we wish to make a directory called ‘ranjeet’ but the directories ‘Softhunt’ and ‘Authors’ aren’t in the path. Then, using the os.makedirs() function, any unavailable/missing directories in the specified path will be created. The ‘Softhunt’ and ‘Authors‘ directories will be established initially, followed by the ‘ranjeet’ directory.

Syntax:

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

In the above Syntax there are four parameters:

  • 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 use 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.

Examples of os.makedirs() method

In this section, we will see how to make a directory and errors which users face during usage.

Example 01: Use of os.makedirs() method to create directory

# Python program to explain os.makedirs() method
   
# importing os module
import os
 
# Leaf directory
directory = "ranjeet"
 
# Parent Directories
parent_dir = "/home/User/Documents/Softhunt/Authors"
 
# Path
path = os.path.join(parent_dir, directory)
 
# Create the directory
# 'ranjeet'
os.makedirs(path)
print("Directory '%s' created" %directory)
 
# Directory 'Softhunt' and 'Authors' will
# be created too
# if it does not exists
 

# Leaf directory
directory = "c"
 
# Parent Directories
parent_dir = "/home/User/Documents/Softhunt/a/b"
 
# mode
mode = 0o666
 
path = os.path.join(parent_dir, directory)
 
# Create the directory
# 'c'
  
os.makedirs(path, mode)
print("Directory '%s' created" %directory)
 

# 'Softhunt', 'a', and 'b'
# will also be created if
# it does not exists
# If any of the intermediate level
# directory is missing
# os.makedirs() method will
# create them
# os.makedirs() method can be
# used to create a directory tree

Output:

img1

Example 02: Errors while using os.makedirs() method

# 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

	
# Directory
directory = "ranjeet"

# Parent Directory path
parent_dir = "/home/User/Documents/Softhunt"

# Path
path = os.path.join(parent_dir, directory)

# Create the directory
# 'ranjeet'
os.makedirs(path)
print("Directory '%s' created" %directory)

Output:

img2

Example 03: Handling errors while using os.makedirs() method

# 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 = "ranjeet"

# Parent Directory path
parent_dir = "/home/ranjeet/Desktop/Softhunt"

# Path
path = os.path.join(parent_dir, directory)

# Create the directory
# 'ranjeet'
try:
	os.makedirs(path, exist_ok = True)
	print("Directory '%s' created successfully" %directory)
except OSError as error:
	print("Directory '%s' can not be created")


# By setting exist_ok as True
# error caused due already
# existing directory can be suppressed
# but other OSError may be raised
# due to other error like
# invalid path name

Output:

img3

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. How to read JSON in Python
  2. How to Connect Python with Database
  3. Python Tuple [With Examples]

Leave a Comment