How can I create directories recursively? [duplicate]

starting from python 3.2 you can do this:

import os
path="/home/dail/first/second/third"
os.makedirs(path, exist_ok=True)

thanks to the exist_ok flag this will not even complain if the directory exists (depending on your needs….).


starting from python 3.4 (which includes the pathlib module) you can do this:

from pathlib import Path
path = Path('/home/dail/first/second/third')
path.mkdir(parents=True)

starting from python 3.5 mkdir also has an exist_ok flag – setting it to True will raise no exception if the directory exists:

path.mkdir(parents=True, exist_ok=True)

Leave a Comment