Create Directory In Python

In this short guide, I’ll show you different ways for how to create directory in python. So without wasting any further time let’s get started.

Create Directory In Python By Using Os Module

The os is the builtin module in python that provides a couple of useful functions to interact with the operating system. The os.mkdir() and os.makedirs() are two functions provided by os module to create directories in python.

1. By Using os.mkdir

os.mkdir() takes a string path as an argument and creates a directory at the given path and it raises Error if the directory already exists.

Below code will create the directory at current working directory.

# program to create directory in python
import os

# create a directory with the name of MyDir.
os.mkdir("MyDir")

It will raise FileExistsError if the directory already exists. So to prevent that error it’s a good idea to wrap the code inside the try-except block.

try:
    os.mkdir("MyDir") # try to create dir
except FileExistsError: # if dir already exists
    print("Directory Already Exists")

Here is the output of the above code.

Output :

Output of program to create directory in python

Or you can also use os.path.exists() function to check if the directory or file already exists or not.

if not os.path.exists("MyDir"): # check if dir already exists or not
    os.mkdir("MyDir")
else:
    print("Directory Already Exists")

If you try to create a directory with some intermediate path in it for example “folder1/folder2/New Dir” and folder1 or folder2 does not exist then os.mkdir will raise the FileNotFoundError.

os.mkdir("folder1/folder2/test")

If folder1 or folder2 did not exists It will raise the below error.

FileNotFoundError: [WinError 3] The system cannot find the path specified: 'folder1/folder2/test'

To solve this problem the os module provides us os.makedirs function that will also intermediate directories if it does not exists.

2. By Using os.makedirs()

The os.makedirs takes a path as an argument and creates a directory and raises error if it already exists.

# this is the better approach to create directory in python
os.makedirs("folder1/folder2/test")

Along with “Test”, it will also create folder1 and folder2 directories if it does not exists.

Leave a Reply