Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to make all dirs in a path

Tags:

python

path

Here are four paths:

p1=r'\foo\bar\foobar.txt' p2=r'\foo\bar\foo\foo\foobar.txt' p3=r'\foo\bar\foo\foo2\foobar.txt' p4=r'\foo2\bar\foo\foo\foobar.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.

like image 281
marw Avatar asked Mar 06 '11 13:03

marw


People also ask

How can I safely create a nested directory?

Example 1: Using pathlib.mkdir to create a nested directory. Import class Path from pathlib library. Call the module mkdir() with two arguments parents and exist_ok . By default, parents is set False .

What is Exist_ok true?

The exist_ok parameter (Python 3.2 or later) If exist_ok=True , you can specify an existing directory without error. Note that the default is exist_ok=False . In older versions without exist_ok , you can use try to handle exceptions, or use os.

Is Makedirs recursive?

Python method makedirs() is recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory.


2 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().

like image 125
David Heffernan Avatar answered Sep 21 '22 16:09

David Heffernan


On Python 3.6+ you can do:

import pathlib  path = pathlib.Path(p4) path.parent.mkdir(parents=True, exist_ok=True) 
like image 43
axwell Avatar answered Sep 21 '22 16:09

axwell