The Python os.makedirs() method is a recursive directory creation function. It works similarly to mkdir(), but makes all intermediate-level directories needed to contain the leaf directory.
With the release of Python 3.2 version, a new parameter was introduced named exist_ok. The default value of this parameter is "False". It will raise a FileExistsError if the target directory already exists.
SyntaxFollowing is the syntax for Python os.makedirs() method −
os.makedirs(path, mode=0o777, exist_ok=False)Parameters
The Python os.makedirs() method accepts the following parameters −
path − This parameter specifies a path which needs to be created recursively.
mode − It is an optional parameter that represents mode of the given directories.
exist_ok − It is an optional parameter that is represented by a Boolean value. When present throws a FileExists error if the specified directory already exists and value is set to False.
The Python os.makedirs() method does not return any value.
ExampleThe following example shows the usage of makedirs() method. Here, we create multiple nested directories with a mode "0o777". It means the created directories are readable, writable, and executable by every user type.
import os, sys # Path to be created path = "/home/tp/Python/tmp/new/monthly/daily" os.makedirs( path, 0o755 ); print ("Path is created")
When we run the above program, it will create multiple directories nested one inside another and print the following result −
Path is createdExample
The makedirs() method raises "FileExists" error if the specified directory already exists. The below example illustrates the same.
import os, sys # Path to be created path = "/home/tp/Python/tmp/new/monthly/daily" try: os.makedirs(path) print ("Path created successfully") except FileExistsError as err: print(f"Error: {err}") except OSError as err: print(f"Error: {err}")
When we run above program, it produces following result −
Error: [Errno 17] File exists: '/home/tp/Python/tmp/new/monthly/daily'
python_files_io.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4