0

I would like to create a hierarchy of directories, if they do not exist.

For example; imagine the path /tmp/myfolder/myclients

If myfolder exists, I can just use os.mkdir to create myclients folder, if it does not exist; but how do I create myfolder too, in case it does not exist? Because os.mkdir does trigger an error if I try to create myclients inside myfolder, if myfolder does not exist

Should I make a call for each folder that is nested and create folders as I go, or there is a more efficient way to do this?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

1

You can use os.makedirs() instead of os.mkdir() which will create all missing directories in the path. As the manual says

Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory.

Also answered here.

marekful
  • 14,986
  • 6
  • 37
  • 59
  • Thanks a lot! I would get from google only the version without the extra `s` –  Aug 20 '19 at 01:23
  • It's not just the plural but `mkdir` vs `makedirs`. By the way, the latter is just below the former in the reference manual. ;) – marekful Aug 20 '19 at 08:23