Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Create a Directory Using Python



In Python the os module provides two methods for creating a directory they are os.mkdir() and os.makedirs(), we can create a Single directory by using os.mkdir() method and by using the os.makedirs() method we can create Subdirectories.

To use those two methods, we need to include the os module, which allows us to interact with the operating system. The two common approaches to creating a directory using Python are as follows.

  • Using 'os.mkdir()' Method: To Create a Single Directory

  • Using 'os.makedirs()' Method: To Create a directory with Subdirectories.

Using 'os.mkdir()' Method

We can create a single directory using os.mkdir() method. This os.mkdir() method accepts only one argument while specifying the path for the directory.

import os

# specify the path for the directory
path = './my_project'

# creating single directory
os.mkdir(path)

The above code will create a directory named 'my_project' and ./ stands for the current working directory.

Handling Exceptions while using the 'os.mkdir' method

A FileExistsError exception is raised when we try to create a file which is already exists.

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    os.mkdir(path)
FileExistsError: [Errno 17] File exists: './my_project'

To handle this exception we can use the if..else block to check if the file already exists.

import os

path = './my_project'

# To check that directory already exists
if not os.path.exists(path):
   os.mkdir(path)
   print("Folder %s created!" % path)
else:
   print("Folder %s already exists" % path)

From the above example, by using os.path.exists() method we can check whether ./my_project directory already exists.

In case the directory exists then instead of FileExistsError we get the following output -

Folder ./my_project already exists

If doesn't exist, then a new my_project folder was created in the current working directory.

Folder ./my_project created!

Using 'os.makedirs()' Method

We can create a directory with sub-directories or nested directory structure by using os.makedirs(). The os.makedirs() accepts one argument for the entire folder path that you are going to create.

import os

# defining the name of the directory along with its subdirectories
path = './my_project/new_folder/game01'

os.makedirs(path)

Handling Exceptions while using 'os.makedirs()' method

We can use the Python idiom EAFP stands for Easier to ask for forgiveness than permission. The below example code describes, handling the exception by using try/except block.

Example

import os
try:
    os.makedirs('my_folder')
except OSError as e:
    if e.errno != errno.EEXIST:
        raise
Updated on: 2024-11-13T12:58:54+05:30

556 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements