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("someDirectory")

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"):
    os.mkdir(dirName)

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

import os
os.makedirs("someDir/sub-dir/sub-sub-dir")

Output

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

About the author

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