When working with Python, you may need to create a directory for various purposes. In this article, we will explore how to create a directory using the os.mkdir() method provided by the os standard library module.

To get started, import the os module:

import os

Next, specify the desired directory path:

dirname = '/Users/flavio/test'

Now, let’s use the os.mkdir() method to create the directory:

os.mkdir(dirname)

However, it’s important to note that creating a folder can sometimes raise an OSError exception. This can occur if the disk is full or if the directory already exists. To handle such situations gracefully, we can use a try-except block. Here’s an example:

import os

dirname = '/Users/flavio/test'

try:
    os.mkdir(dirname)
except OSError:
    print('Failed to create the directory')
else:
    print('Directory created successfully')

In the above code snippet, we attempt to create the directory using os.mkdir(). If an OSError occurs, the except block will catch the exception and print an error message. Otherwise, the else block will be executed, indicating that the directory was created successfully.

Remember to replace '/Users/flavio/test' with the desired path for your directory.

Now you know how to create a directory in Python using the os.mkdir() method. Good luck with your future projects!