Python os.makedirs() Method

Python os.makedirs() method is used to create a directory at the specified path. It can also be used to create all intermediate-level directories that contain the leaf directory.

Unlike os.mkdir(), os.makedirs() can create intermediate directories in the path if they don’t exist.

This method is specifically helpful for creating profoundly nested directory structures and ensuring that a full path of directories exists without manually checking and creating each level of the directory structure.

Syntax

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

Parameters

Name Description
name (string) It is a path of the directory to be created.
mode (optional) It is the mode of the directory to be created. The default mode is 0o777 (octal notation), allowing read, write, and execute permission for the owner, group, and others. The current umask value is first masked out.
exists_ok (optional) If exist_ok is False (the default), a FileExistsError is raised if the target directory already exists. If exist_ok is True, no error is raised, and the function completes successfully even if the directory exists.

Return value

This method does not return any value.

Example 1: Creating a Directory with Intermediate Directories

Visual Representation of Python os.makedirs() Method

import os

path = '/Users/krunallathiya/Desktop/Code/pythonenv/env/newdir/basic'

os.makedirs(path)

print("Directory created at:", path)

Output

Directory created at: /Users/krunallathiya/Desktop/Code/pythonenv/env/newdir/basic

Output of Python os.makedirs() Method

Example 2: While creating a directory, ignoring If it exists

import os

path = '/Users/krunallathiya/Desktop/Code/pythonenv/env/newdir/basic'

os.makedirs(path, exist_ok=True)

print("Directory created at:", path)

Output

Directory created at: /Users/krunallathiya/Desktop/Code/pythonenv/env/newdir/basic

Here, this function is used with exist_ok=True, which means the function will not raise an error if the directory exists.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.