如何在 Python 中使用 -p 选项运行 os.mkdir()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16029871/
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-18 21:38:27  来源:igfitidea点击:

How to run os.mkdir() with -p option in Python?

pythonmkdir

提问by pynovice

I want to run mkdircommand as:

我想运行mkdir命令:

mkdir -p directory_name

What's the method to do that in Python?

在 Python 中这样做的方法是什么?

os.mkdir(directory_name [, -p]) didn't work for me.

采纳答案by Adem ?zta?

You can try this:

你可以试试这个:

# top of the file
import os
import errno

# the actual code
try:
    os.makedirs(directory_name)
except OSError as exc: 
    if exc.errno == errno.EEXIST and os.path.isdir(directory_name):
        pass

回答by singer

Something like this:

像这样的东西:

if not os.path.exists(directory_name):
    os.makedirs(directory_name)

UPD: as it is said in a comments you need to check for exception for thread safety

UPD:正如评论中所说,您需要检查线程安全的异常

try:
    os.makedirs(directory_name)
except OSError as err:
    if err.errno!=17:
        raise

回答by pitfall

how about this os.system('mkdir -p %s' % directory_name )

这个怎么样 os.system('mkdir -p %s' % directory_name )

回答by Michael Ma

According to the documentation, you can now use this since python 3.2

根据文档,您现在可以从 python 3.2 开始使用它

os.makedirs("/directory/to/make", exist_ok=True)

and it will not throw an error when the directory exists.

并且当目录存在时它不会抛出错误。

回答by Boris

If you're using pathlib, use Path.mkdir(parents=True, exist_ok=True)

如果您正在使用pathlib,请使用Path.mkdir(parents=True, exist_ok=True)

from pathlib import Path

new_directory = Path('./some/nested/directory')
new_directory.mkdir(parents=True, exist_ok=True)

parents=Truecreates parent directories as needed

parents=True根据需要创建父目录

exist_ok=Truetells mkdir()to not error if the directory already exists

exist_ok=Truemkdir()如果目录已经存在,则告诉不要出错

See the pathlib.Path.mkdir()docs.

请参阅pathlib.Path.mkdir()文档