Python - How to create directory

By xngo on June 16, 2019

In Python, creating a directory is easy. Simply run the following code.

import os

os.mkdir() will throw an error if the directory already exists. So, to avoid the error, check whethere the directory exists or not before creating it.

import os
# Create directory only it doesn't exists.
if not os.path.exists("someDirectory"):

Python also provides a convenient method to create all intermediate directories for you.

import os


└── sub-dir
    └── sub-sub-dir

About the author

Xuan Ngo is the founder of He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.