Python3 os.makedirs() Method
Python3 OS File/Directory Methods
Overview
The os.makedirs()
method is used to recursively create multi-level directories.
If the subdirectory creation fails or already exists, an OSError exception is raised. On Windows, Error 183 is the exception error for an already existing directory.
If the first parameter path
only has one level, meaning it only creates one directory, it is the same as the mkdir()
function.
Syntax
The syntax for the makedirs() method is as follows:
os.makedirs(name, mode=511, exist_ok=False)
Parameters
-
path -- The directory to be recursively created, which can be a relative or absolute path.
-
mode -- The permission mode, with the default mode being 511 (octal).
- exist_ok -- Whether to raise an exception if the directory already exists. If
exist_ok
is False (default), aFileExistsError
exception is raised if the target directory already exists; ifexist_ok
is True, noFileExistsError
exception is raised if the target directory already exists.
Return Value
This method does not return a value.
Example
The following example demonstrates the use of the makedirs()
method:
Example
#!/usr/bin/python3
import os, sys
# Directory to be created
path = "/tmp/home/monthly/daily"
os.makedirs(path, 0o777)
print("Path created")
Executing the above program outputs:
Path created