Linux os的makedirs和mkdir有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13819496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:01:14  来源:igfitidea点击:

What is different between makedirs and mkdir of os?

pythonlinuxpython-2.7

提问by Toni

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

我很困惑使用这两种os方法来创建新目录。

Please give me some example in Python.

请给我一些 Python 示例。

回答by NPE

makedirs()creates all the intermediate directoriesif they don't exist (just like mkdir -pin bash).

makedirs()如果它们不存在,则创建所有中间目录(就像mkdir -p在 bash 中一样)。

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

mkdir()可以创建单个子目录,如果指定了不存在的中间目录,则会抛出异常。

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

两者都可用于创建单个“叶”目录(dirA):

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

But makedirs must be used to create 'branches':

但是必须使用 makedirs 来创建“分支”:

  • os.makedirs('dirA/dirB')will work [the entire structure is created]
  • os.makedirs('dirA/dirB')将工作 [整个结构已创建]

mkdircan work here ifdirAalready exists, but if it doesn't an error will be thrown.

mkdir如果dirA已经存在,可以在这里工作,但如果不存在,则会抛出错误。

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

请注意,与mkdir -pbash不同的是,如果叶子已经存在,则两者都将失败。

回答by Yunqing Gong

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

(无法评论,只需添加到 NPE 的答案中。)

In Python3, os.makedirshas a default parameter exist_ok=False.
If you set it to True, then os.makedirswill notthrow any exception if the leaf exists.
(While os.mkdirdoesn't have this parameter.)

在 Python3 中,os.makedirs有一个默认参数exist_ok=False
如果你把它设置为True,那么os.makedirs若叶存在抛出任何异常。
(虽然os.mkdir没有这个参数。)

Just like this:

像这样:

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

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

PS
您可以?在 IPython shell 中的方法名称之前键入以快速查看文档。
例如:

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