Let's study Python

Use os.mkdir() in Python to effortlessly create new directories with ease.

# Python os.mkdir Usage

In Python, the `os.mkdir()` function is used to create a new directory. It takes the path of the directory as an argument and creates a new directory at that location. If the directory already exists, `os.mkdir()` will raise a `FileExistsError` exception.

## Syntax

The syntax for `os.mkdir()` is as follows:

“`python
import os

os.mkdir(path)
“`

Where `path` is the path of the directory to be created.

## Example

Let’s look at an example to see how `os.mkdir()` is used in Python:

“`python
import os

# Specify the path of the directory to be created
path = “/path/to/new/directory”

try:
os.mkdir(path)
print(“Directory created successfully”)
except FileExistsError:
print(“Directory already exists”)
“`

In this example, we import the `os` module and then specify the path of the directory we want to create. We use a `try` block to attempt to create the directory using `os.mkdir()`. If the directory already exists, a `FileExistsError` exception is raised and we handle it by printing out a message.

## Additional Arguments

The `os.mkdir()` function also accepts additional optional arguments to set the mode and flags of the newly created directory. The mode argument specifies the permissions of the directory, while the flags argument specifies additional options for the operation.

## Error Handling

As mentioned earlier, if the directory specified by the `path` argument already exists, `os.mkdir()` will raise a `FileExistsError` exception. It is important to handle this exception to prevent your program from crashing. You can use a `try` block to catch the exception and handle it accordingly.

## Permissions

By default, the permissions of the newly created directory are set based on the current umask value. You can use the `os.chmod()` function to change the permissions of the directory after creating it.

## Conclusion

In this guide, we have looked at how to use the `os.mkdir()` function in Python to create a new directory. We covered the syntax of the function, provided an example of its usage, discussed additional arguments, error handling, and permissions. By following the guidelines outlined in this guide, you can effectively use `os.mkdir()` in your Python programs to create directories as needed.