Creating directories and handling exceptions in Python

Example of os.mkdir() and os.makedirs() methods: Here, we are going to learn how to create a single or multiple directories in Python, here we are also learning how to handle the exceptions while creating the directories? By Sapna Deraje Radhakrishna Last updated : August 22, 2023

Python os.mkdir() method

The built-in, 'os' module is useful in creating directories. The syntax to create the directory is,

os.mkdir(<path>)

Python code to create directory

# importing the module
import os

#method calling by passing directory name
os.mkdir('test')

The above example creates directory in the current directory.

Exception Handling during directory creation

Step1: Check if the folder exists

# importing the module
import os

# directory name
folder_name = 'test'

# checking whether folder/directory exists
if not os.path.exists(folder_name):
    os.mkdir(folder_name)
    print("folder '{}' created ".format(folder_name))
else:
    print("folder {} already exists".format(folder_name))

Output

folder test already exists

Step2: If the directory already exists, the application will raise a 'FileExistsError' Error. In order to avoid exceptions, it is always advisable to use try/except

# importing the module
import os

# directory name
folder_name = 'test'

# checking whether folder/directory exists
try:
    os.mkdir(folder_name)
    print("folder '{}' created ".format(folder_name))
except FileExistsError:
    print("folder {} already exists".format(folder_name))

Output

folder test already exists

Create directories including the child directories

The syntax 'os.mkdir(<path>)' cannot create an intermediate directory, the given path, if they are not present. The error it throws in such scenarios is,

# importing the module
import os

# creating directory with child directory
# Here, error will generate
os.mkdir('test1/test')

Output

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    os.mkdir('test1/test')
FileNotFoundError: [Errno 2] No such file or directory: 'test1/test'

Note: The os.mkdir() does create a child directory for test1, if test1 was already present.

To create a directory with its child directories, the function 'makedirs()' is used.

# importing the module
import os

# creating directory with child directories
os.makedirs('test/test3')

Exception Handling during directory creation using os.makedirs()

Step1: Check if the folder exists

# importing the module
import os

# creating directory with child directories
folder_name = 'test/test3'
if not os.path.exists(folder_name):
    os.makedirs(folder_name)
    print("folder '{}' created ".format(folder_name))
else:
    print("folder {} already exists".format(folder_name))

Output

folder 'test/test3' already exists

Step2: If the directory already exists, the application will raise a ‘FileExistsError’ Error. In order to avoid exceptions, it is always advisable to use try/except

# importing the module
import os

# creating directory with child directories
folder_name = 'test/test3'

try:
    os.makedirs(folder_name)
    print("folder '{}' created ".format(folder_name))
except FileExistsError:
    print("folder {} already exists".format(folder_name))

Output

folder 'test/test3' already exists

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.