What is different between makedirs and mkdir of os?

PythonLinuxPython 2.7

Python Problem Overview


I am confused to use about these two os methods to create the new directory.

Please give me some example in Python.

Python Solutions


Solution 1 - Python

makedirs() creates all the intermediate directories if they don't exist (just like mkdir -p in bash).

mkdir() can create a single sub-directory, and will throw an exception if intermediate directories that don't exist are specified.

Either can be used to create a single 'leaf' directory (dirA):

  • os.mkdir('dirA')
  • os.makedirs('dirA')

But makedirs must be used to create 'branches':

  • os.makedirs('dirA/dirB') will work [the entire structure is created]

mkdir can work here if dirA already exists, but if it doesn't an error will be thrown.

Note that unlike mkdir -p in bash, either will fail if the leaf already exists.

Solution 2 - Python

(Can not comment, just add to NPE's answer.)

In Python3, os.makedirs has a default parameter exist_ok=False.
If you set it to True, then os.makedirs will not throw any exception if the leaf exists.
(While os.mkdir doesn't have this parameter.)

Just like this:

os.makedirs('dirA', exist_ok=True)

P.S.
You can type ? before the name of a method in IPython shell to take a quick look at the documentation.
e.g.:

>>> import os
>>> ? os.makedirs

Solution 3 - Python

makedirs : 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionToniView Question on Stackoverflow
Solution 1 - PythonNPEView Answer on Stackoverflow
Solution 2 - PythonYunqing GongView Answer on Stackoverflow
Solution 3 - PythonMed_sirajView Answer on Stackoverflow