Elegant way to make all dirs in a path

Question:

Here are four paths:

p1=r'foobarfoobar.txt'
p2=r'foobarfoofoofoobar.txt'
p3=r'foobarfoofoo2foobar.txt'
p4=r'foo2barfoofoofoobar.txt'

The directories may or may not exist on a drive. What would be the most elegant way to create the directories in each path?

I was thinking about using os.path.split() in a loop, and checking for a dir with os.path.exists, but I don’t know it there’s a better approach.

Asked By: marw

||

Answers:

You are looking for os.makedirs() which does exactly what you need.

The documentation states:

Recursive directory creation function.
Like mkdir(), but makes all
intermediate-level directories needed
to contain the leaf directory. Raises
an error exception if the leaf
directory already exists or cannot be
created.

Because it fails if the leaf directory already exists you’ll want to test for existence before calling os.makedirs().

Answered By: David Heffernan

On Python 3.6+ you can do:

import pathlib

path = pathlib.Path(p4)
path.parent.mkdir(parents=True, exist_ok=True)
Answered By: axwell

A simple way to build the paths in POSIX systems. Assume your path is something like: dirPath = '../foo/bar', where neither foo or bar exist:

path = ''
for d in dirPath.split('/'):
   # handle instances of // in string
   if not d: continue 

   path += d + '/'
   if not os.path.isdir(path):
      os.mkdir(path)
   
Answered By: RexBarker
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.