Python

Python How to create a directory (folder) – mkdir, makedirs

arage.com@gmail.com

Python has a variety of modules to handle directories and files, and the most commonly used among them is the os module. The os module provides OS-dependent functionalities, one of which is the ability to perform operations on files and directories.

Creating a Directory

Python’s os module allows us to create a new directory.

Creating a directory with os.mkdir

The os.mkdir function allows you to create a directory. You specify the path of the directory you want to create as an argument.

1import os
2
3os.mkdir("test_directory")

This code creates a directory named “test_directory” under the current directory.

Creating a directory recursively with os.makedirs

The os.makedirs function is similar to the os.mkdir function, but it allows you to create subdirectories at once. This overcomes one of the limitations of mkdir, which returns an error if you specify a non-existent path. makedirs automatically creates intermediate directories.

1import os
2
3os.makedirs("test_directory/sub_directory")

This code creates a directory named “test_directory” and its subdirectory “sub_directory” under the current directory.

Handling the case where the directory already exists

When creating a directory, an error will occur if a directory with the same name already exists. Let’s look at how to handle this appropriately.

In the case of os.mkdir

When creating a directory using the os.mkdir function, an error will occur if a directory with the same name already exists. To avoid this, you can create a directory after checking if it exists.

1import os
2
3if not os.path.exists("test_directory"):
4    os.mkdir("test_directory")

This code creates a directory named “test_directory” only if it does not already exist.

In the case of os.makedirs

Similarly, when creating a directory using the os.makedirs function, an error will occur if a directory with the same path already exists. To avoid this, you can specify the exist_ok=True option.

1import os
2
3os.makedirs("test_directory/sub_directory", exist_ok=True)

This code creates a directory named “test_directory/sub_directory” only if it does not already exist.

By using these techniques, you can handle errors appropriately when creating directories in Python.

記事URLをコピーしました