In this article we will discuss different APIs in python to create directories.

Creating a Directory in Python

Python’s OS module provides a function to create a directory i.e.

It creates a directory with given path i.e.

It creates the directory ‘tempDir’ in current directory.

If directory already exists then it will raise FileExistsError Error. So to avoid errors either we should call it using try / except i.e.

or we should first check if given folder exists or not i.e.

os.mkdir(path) will create the given directory only, but it will not create the intermediate directory in the given path.

For example we want to create ‘temp/tempDir2/sample’ in current working directory. But neither temp or tempDir2 is present in current working directory. Hence it will throw error i.e.


os.mkdir(path) can not create intermediate directories in the given path,if they are not present. It will throws error in such cases. For that we need another API.

Creating Intermediate Directories in Python

Python’s OS module provides an another function to create a directories i.e.

os.makedirs(name) will create the directory on given path, also if any intermediate-level directory don’t exists then it will create that too.

Its just like mkdir -p command in linux.

Let’s create a directory with intermediate directories i.e.

It will create all the directory ‘temp’ and all its parent directories if they don’t exists.

If target directory already exists then it will throw error. So, either call it using try / except i.e.

or before calling check if target directory already exists i.e.

Complete example is as follows,



Click Here to Subscribe for more Articles / Tutorials like this.