# Best Practice to Python Create Directory Recursively – Python Tutorial

By | September 4, 2019

When we are copying, moving or saving files with python, one problem we must concern is: Does the file directory exist? In this tutorial, we will introduce you how to create directories recursively with python.

For example:

If you plan to move file: f:\test.pdf to f:\pdf\1\test.pdf. You must be sure directories pdf and 1 exist. If they do not exist, you will fail to move file.

As to directory f:\pdf\1\, how can we create directory pdf and 1?

## Python create directory recursively

Here we write an example code to create directories recursively in python.

def createDirs(d):
if not os.path.exists(d):
os.makedirs(d)

If directory pdf and 1 do not exist. createDirs() function can create them.

## How to use this function?

createDirs("f:\\pdf\\1")

Then directory pdf and 1 are created.