Python os.mkdir() Method



The mkdir() method is a built-in function of Python OS module that allows us to create a new directory at the specified path. We can also specify the mode for newly created directory. Always remember the default mode is 0o777(octal). On some systems, mode may be ignored.

If we try to create a new directory within a non-existing directory, this method will throw FileNotFoundError. And, If we specify name of an existing directory, it will raise FileExistsError.

The difference between mkdir() and mkdirs() method is that the mkdir() method is used to create a single directory whereas the mkdirs() can create nested directories.

Syntax

Following is the syntax for Python os.mkdir() method −

os.mkdir(path, mode, *, dir_fd)

Parameters

The Python os.mkdir() method accepts the following parameters −

  • path − This is a string or a byte value representing a path, which needs to be created.

  • mode − This is the mode of the directories to be given.

  • dir_fd − This parameter was introduced in the Python version 3.3 and it represents a file descriptor that refers to a directory. Its default value is "None".

  • * − This parameter indicates that all following parameters (in this case, dir_fd) are keyword-only parameters.

Return Value

The Python os.mkdir() method does not return any value.

Example

In this example, we are creating a directory named "monthly" using the mkdir() method. Here, we have specified the mode as "0o755" which sets the directory permission to read, write and execute.

import os, sys

# Path to be created
path = "/home/tp/Python/tmp/new/monthly"

os.mkdir( path, 0o755 );
print ("Path is created")

When we run above program, it produces following result −

Path is created

Example

As stated earlier, if the specified directory already exists, a FileExistsError will be raised. The following example demonstrates the same.

import os, sys

# Path to be created
path = "/home/tp/Python/Tutorials"

try:
   os.mkdir( path, 0o755 );
   print ("Path created successfully")
except FileExistsError as err:
   print(f"Error: {err}")
except OSError as err:
   print(f"Error: {err}")

When we execute the above program, it will produces the following error −

Error: [Errno 17] File exists: '/home/tp/Python/Tutorials'
python_files_io.htm
Advertisements