Python3 os.makedirs() Method

Python3 OS File/Directory Methods


Overview

The os.makedirs() method is used to recursively create multi-level directories.

If a subdirectory creation fails or already exists, an OSError exception will be raised. On Windows, Error 183 is the exception error indicating that the directory already exists.

If the first parameter path has only one level, i.e., only one directory level is created, then it is the same asmkdir()the function.

Syntax

makedirs()The method syntax is as follows:

os.makedirs(name, mode=511, exist_ok=False)

Parameters

  • path-- The directory to be recursively created, can be a relative or absolute path.

  • mode-- Permission mode, the default mode is 511 (octal).

  • exist_ok: Whether to trigger an exception when the directory exists. If exist_ok is False (default), a FileExistsError exception is raised when the target directory already exists; if exist_ok is True, a FileExistsError exception will not be raised when the target directory already exists.

Return Value

This method has no return value.

Example

The following example demonstrates the use of the makedirs() method:

Example

#!/usr/bin/python3

import os, sys

# The directory to be created
path = "/tmp/home/monthly/daily"

os.makedirs( path, 0o777 );

print ("path was created")

The output after running the above program is:

The path was created.

Python3 OS File/Directory Methods

Other Extensions