To create a new directory using os.mkdir()
, you need to pass in the path of the directory you want to create as a parameter. Here’s an example:
import os
# Specify the path of the new directory
new_directory_path = '/path/to/new/directory'
# Create the new directory
os.mkdir(new_directory_path)
In the code above, we first import the os
module. Then, we specify the path where we want to create the new directory by assigning it to the new_direcetory_path
variable. Finally, we call the os.mkdir()
function and pass in the path to create the directory.
Important things to note:
- Make sure the path you provide is valid and doesn’t contain any invalid characters.
- If the directory already exists,
os.mkdir()
will raise aFileExistsError
. So, it’s a good practice to check if the directory exists before creating it.
You can use os.path.exists()
function to check if a directory already exists, like this:
if not os.path.exists(new_directory_path):
os.mkdir(new_directory_path)
This will prevent any errors if you try to create a directory that already exists.
Creating a new directory using os.mkdir()
is a simple and straightforward process. With this function, you can easily manage file system operations in your Python projects.