/

How to Create a Directory in Python

How to Create a Directory in Python

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:

1
import os

Next, specify the desired directory path:

1
dirname = '/Users/flavio/test'

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

1
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:

1
2
3
4
5
6
7
8
9
10
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!

tags: [“Python”, “directory”, “os module”, “mkdir method”]