In this tutorial, we will be exploring the Python method
os.mkdir(). This function is part of the os module and allows us to create directories (folders) in our file system. Let’s dive right in!
Importing the Required Module
To use the
os.mkdir() method, you first need to import the os module. Here is how you do it:
<script> import os </script>
The Syntax of os.mkdir()
The syntax for using
os.mkdir() is quite simple:
<script> os.mkdir(path, mode=0o777, *, dir_fd=None) </script>
- path: This is a string that defines the directory to be created.
- mode (optional): The mode parameter determines the permissions for the directory. By default, it’s set to 0o777.
- dir_fd (optional): If provided, it should be a file descriptor referring to a directory.
A Basic Example of Using os.mkdir()
This example demonstrates how to create a new directory named “new_directory” in your current working directory:
<script> import os # Define the name of the directory to be created path = "./new_directory" # Create new directory os.mkdir(path) </script>
Error Handling with os.mkdir()
If the directory you’re trying to create already exists,
os.mkdir() will raise a
FileExistsError. To avoid this, you can use an if statement to check whether the directory already exists:
<script> import os # Define the name of the directory to be created path = "./new_directory" # Check if the directory already exists if not os.path.exists(path): # Create new directory os.mkdir(path) else: print("Directory already exists.") </script>
os.mkdir() method is a powerful tool for creating directories in your file system. With its simple syntax and flexibility, it’s an essential part of any Python programmer’s toolkit.
We hope this tutorial has been helpful in understanding how to use this function. Happy coding!