What is different between makedirs and mkdir of os?

后端 未结 2 1122
挽巷
挽巷 2020-12-28 11:17

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

Please give me some example in Python.

2条回答
  •  遥遥无期
    2020-12-28 12:19

    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.

提交回复
热议问题