如何在Python中安全地创建嵌套目录?

如何在Python中安全地创建嵌套目录?,python,exception,path,directory,operating-system,Python,Exception,Path,Directory,Operating System,检查文件将要写入的目录是否存在,如果不存在,使用Python创建目录,最优雅的方法是什么?以下是我尝试过的: import os file_path = "/my/directory/filename.txt" directory = os.path.dirname(file_path) try: os.stat(directory) except: os.mkdir(directory) f = file(filename) 不知怎的,我错过了os.pat

检查文件将要写入的目录是否存在,如果不存在,使用Python创建目录,最优雅的方法是什么?以下是我尝试过的:

import os

file_path = "/my/directory/filename.txt"
directory = os.path.dirname(file_path)

try:
    os.stat(directory)
except:
    os.mkdir(directory)       

f = file(filename)
不知怎的,我错过了os.path.exists,谢谢kanja、Blair和Douglas。这就是我现在拥有的:

def ensure_dir(file_path):
    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):
        os.makedirs(directory)
是否有一个“打开”的标志,可以自动执行此操作?

尝试此功能

检查:确保存在完整的路径。 要处理目录可能存在的事实,请捕获OSError。 如果默认情况下exist\ U ok为False,则如果目标目录已存在,则会引发操作错误

import os
try:
    os.makedirs('./path/to/somewhere')
except OSError:
    pass
关于Python≥ 3.5、使用:

对于较旧版本的Python,我看到了两个很好的答案,每个答案都有一个小缺陷,因此我将给出我的看法:

<>试一下,考虑一下创作。

import os
if not os.path.exists(directory):
    os.makedirs(directory)
如注释和其他地方所述,存在竞争条件–如果在os.path.exists和os.makedirs调用之间创建目录,则os.makedirs将失败,并出现操作错误。不幸的是,捕获OSError并继续并不是万无一失的,因为它将忽略由于其他因素(如权限不足、磁盘已满等)而导致的创建目录失败

一种选择是捕获操作错误并检查嵌入的错误代码,请参见:

或者,可能存在第二个os.path.exists,但是假设另一个在第一次检查之后创建了目录,然后在第二次检查之前将其删除——我们仍然可能被愚弄

根据应用程序的不同,并发操作的危险可能大于或小于其他因素(如文件权限)造成的危险。在选择实现之前,开发人员必须更多地了解正在开发的特定应用程序及其预期环境

Python的现代版本通过在3.3+中公开和

try:
    os.makedirs("path/to/directory")
except FileExistsError:
    # directory already exists
    pass
…并允许使用3.2+


我已记下以下内容。不过,这并不是万无一失的

import os

dirname = 'create/me'

try:
    os.makedirs(dirname)
except OSError:
    if os.path.exists(dirname):
        # We are nearly safe
        pass
    else:
        # There was an error on creation, so make sure we know about it
        raise

现在,正如我所说,这并不是万无一失的,因为我们有可能无法创建目录,并且在这段时间内还有另一个创建目录的过程。

我个人建议您使用os.path.isdir来测试,而不是os.path.exists

如果您有:

>>> dir = raw_input(":: ")
和愚蠢的用户输入:

:: /tmp/dirname/filename.etc

。。。如果使用os.path.exists进行测试,则将该参数传递给os.makedirs时,您将得到一个名为filename.etc的目录。

使用try-except和errno模块中的正确错误代码可以消除竞争条件,并且是跨平台的:

import os
import errno

def make_sure_path_exists(path):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise
换句话说,我们尝试创建目录,但如果它们已经存在,我们将忽略错误。另一方面,会报告任何其他错误。例如,如果您事先创建了dir'a'并从中删除了所有权限,则会出现一个操作错误,错误为errno.EACCES Permission denied,错误为13。

Python 3.5+: 如上所述,递归创建目录,如果目录已经存在,则不会引发异常。如果不需要或不希望创建父对象,请跳过parents参数

Python 3.2+: 使用pathlib:

如果可以,请安装名为的当前pathlib backport。不要安装名为的旧的未维护的后端口。接下来,参考上面的Python3.5+部分,并使用相同的方法

如果使用Python3.4,即使它附带了pathlib,它也缺少有用的exist\u ok选项。backport旨在提供一个更新、更高级的mkdir实现,其中包括这个缺少的选项

使用操作系统:

如上所述,递归创建目录,如果目录已经存在,则不会引发异常。只有在使用Python 3.2+时,它才具有可选的exist_ok参数,默认值为False。Python2.x到2.7版本中不存在此参数。因此,不需要像Python 2.7那样进行手动异常处理

Python 2.7+: 使用pathlib:

如果可以,请安装名为的当前pathlib backport。不要安装名为的旧的未维护的后端口。接下来,参考上面的Python3.5+部分,并使用相同的方法

使用操作系统:

虽然一个简单的解决方案可能先使用,然后使用,但上面的解决方案颠倒了两个操作的顺序。在这样做时,它可以防止与创建目录的重复尝试有关的常见争用条件,还可以消除目录中文件的歧义

请注意,捕获异常并使用errno的用处有限,因为存在OSError:[errno 17]文件,即errno.EEXIST,它同时针对文件和目录提出。更可靠的方法是简单地检查目录是否存在

备选方案: 创建嵌套目录,如果该目录已存在,则不执行任何操作。这在Python2和Python3中都适用

import distutils.dir_util
distutils.dir_util.mkpath(path)
根据,此替代方案的一个严重限制是,对于给定路径,每个python进程只工作一次。换句话说,如果您使用它来创建 创建一个目录,然后从Python内部或外部删除该目录,然后再次使用mkpath重新创建同一目录,mkpath只会静默地使用其先前创建该目录的无效缓存信息,而不会再次实际创建该目录。相比之下,os.makedirs不依赖任何这样的缓存。对于某些应用程序,此限制可能没有问题

关于目录的模式,如果您关心它,请参阅文档。

建议使用。这意味着代码

try:
    os.makedirs(path)
except OSError as exception:
    if exception.errno != errno.EEXIST:
        raise
    else:
        print "\nBE CAREFUL! Directory %s already exists." % path
比另一个更好

if not os.path.exists(path):
    os.makedirs(path)
else:
    print "\nBE CAREFUL! Directory %s already exists." % path
文件表明这正是因为这个问题中讨论的竞争条件。此外,正如其他人在这里提到的,查询一次而不是两次操作系统具有性能优势。最后,在某些情况下(当开发人员知道应用程序正在运行的环境时),可能支持第二个代码的论点只能在程序为自身和同一程序的其他实例设置私有环境的特殊情况下提出

即使在这种情况下,这也是一种糟糕的做法,可能会导致长期无用的调试。例如,我们为一个目录设置权限的事实不应该给我们留下这样的印象:权限是为我们的目的而适当设置的。可以使用其他权限装载父目录。一般来说,程序应该始终正常工作,程序员不应该期望某个特定的环境

检查目录是否存在,必要时创建它

对此的直接答案是,假设一个简单的情况,即您不希望其他用户或进程干扰您的目录:

if not os.path.exists(d):
    os.makedirs(d)
import os,sys,inspect
import pathlib

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
your_folder = currentdir + "/" + "your_folder"

if not os.path.exists(your_folder):
   pathlib.Path(your_folder).mkdir(parents=True, exist_ok=True)
或者,如果创建目录受到竞争条件的约束,即如果在检查路径存在后,其他因素可能已经使其执行此操作:

import errno
try:
    os.makedirs(d)
except OSError as exception:
    if exception.errno != errno.EEXIST:
        raise
但也许更好的方法是通过以下途径使用临时目录来回避资源争用问题:

以下是在线文档中的要点:

Python3.5中新增的:带有exist_ok的pathlib.Path 从3.4开始,有一个新的Path对象,其中有许多方法可以用于Path,其中之一就是mkdir

在上下文中,我用脚本跟踪我的每周销售代表。下面是脚本中的相关代码部分,它们允许我避免对同一数据每天多次出现堆栈溢出

首先,有关进口:

from pathlib import Path
import tempfile
我们现在不必处理os.path.join-只需使用/:

然后我以幂等方式确保目录存在-exist_ok参数在Python 3.5中显示:

directory.mkdir(exist_ok=True)
以下是报告的相关部分:

如果exist_ok为true,FileExistsError异常将被忽略,其行为与POSIX mkdir-p命令相同,但仅当最后一个路径组件不是现有的非目录文件时

这里是脚本的更多部分-在我的例子中,我不受竞争条件的约束,我只有一个进程希望目录或包含的文件在那里,并且我没有任何尝试删除目录的内容

todays_file = directory / str(datetime.datetime.utcnow().date())
if todays_file.exists():
    logger.info("todays_file exists: " + str(todays_file))
    df = pd.read_json(str(todays_file))
路径对象必须先强制为str,其他期望str路径的api才能使用它们

也许应该更新Pandas,以接受抽象基类os.PathLike的实例。

了解这种情况的细节 在特定路径上指定一个特定文件,然后从文件路径中提取目录。然后,在确保您拥有该目录后,尝试打开一个文件进行读取。要对此代码进行评论,请执行以下操作:

我们希望避免覆盖内置函数dir。此外,filepath或fullfilepath可能是比filename更好的语义名称,因此编写它会更好:

import os
filepath = '/my/directory/filename.txt'
directory = os.path.dirname(filepath)
您的最终目标是打开此文件(您最初声明)以供编写,但您基本上是基于这样的代码来实现此目标的,这将打开文件以供阅读:

假设开放阅读 为什么要为一个文件创建一个目录,您希望它在那里并且能够读取

只需尝试打开文件

with open(filepath) as my_file:
    do_stuff(my_file)
如果目录或文件不在那里,您将得到一个带有相关错误号的IOError:errno.enoint将指向正确的错误号,而不管您的平台是什么。如果需要,您可以捕获它,例如:

import errno
try:
    with open(filepath) as my_file:
        do_stuff(my_file)
except IOError as error:
    if error.errno == errno.ENOENT:
        print 'ignoring error because directory or file is not there'
    else:
        raise
假设我们开放写作 这可能是你想要的

在这种情况下,我们可能不会面临任何比赛条件。所以只需按原样操作,但请注意,对于编写,您需要使用w模式或a模式打开以进行追加。使用上下文管理器打开文件也是Python的最佳实践

import os
if not os.path.exists(directory):
    os.makedirs(directory)
with open(filepath, 'w') as my_file:
    do_stuff(my_file)
但是,假设我们有几个Python进程,它们试图将所有数据放在同一个目录中。然后我们可能会对目录的创建产生争用。在这种情况下,最好将makedirs调用封装在try-except块中

import os
import errno
if not os.path.exists(directory):
    try:
        os.makedirs(directory)
    except OSError as error:
        if error.errno != errno.EEXIST:
            raise
with open(filepath, 'w') as my_file:
    do_stuff(my_file)

在Python 3.4中,还可以使用:

我看到了和的答案,想到了这一点 变异

import os
import errno

def make_sure_path_exists(path):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST or not os.path.isdir(path):
            raise

对于单衬里解决方案,您可以使用:

从:确保目录存在。如果它不存在,请尝试创建它,并在其他进程执行相同操作时防止竞争条件。

您可以使用os.listdir执行此操作:

import os
if 'dirName' in os.listdir('parentFolderPath')
    print('Directory Exists')
你可以用

注意,它还将创建祖先目录


它适用于Python 2和3。

如果你考虑以下内容:

import distutils.dir_util
distutils.dir_util.mkpath(path)
os.path.isdir('/tmp/dirname')
表示存在一个目录路径,并且是一个目录。所以对我来说,这种方式满足了我的需要。因此,我可以确保它是文件夹而不是文件并且存在。

从Python 3.5开始,有一个exist\u ok标志:

这将递归地创建目录,如果目录已经存在,则不会引发异常

import os
try:
    os.makedirs('./path/to/somewhere')
except OSError:
    pass
正如从Python3.2开始得到一个exist_ok标志一样,例如os.makedirspath,exist_ok=True

注意:当我发布这个答案时,其他提到的答案都不存在。\u ok…

在Python3中,os.makedirs支持设置exist\u ok。默认设置为False,这意味着如果目标目录已存在,将引发操作错误。通过将exist_ok设置为True,将忽略OSError目录exists,并且不会创建该目录

os.makedirs(path,exist_ok=True)
在Python2中,os.makedirs不支持设置exist\u ok。您可以在以下情况下使用该方法:

我使用os.path.exists,它是一个Python 3脚本,可以用来检查目录是否存在,如果不存在则创建一个目录,如果确实存在则删除它(如果需要)

它提示用户输入目录,并且可以轻松修改

import os
if os.path.isfile(filename):
    print "file exists"
else:
    "Your code here"
此处的代码使用触摸命令


这将检查文件是否存在,如果不存在,它将创建它。

我发现了这个Q/A,最初我对一些失败和错误感到困惑。我正在Arch Linux x86_64系统上的Anaconda虚拟环境中使用Python 3 v.3.5

考虑以下目录结构:

└── output/         ## dir
   ├── corpus       ## file
   ├── corpus2/     ## dir
   └── subdir/      ## dir
以下是我的实验/笔记,它澄清了一些事情:

# ----------------------------------------------------------------------------
# [1] https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist

import pathlib

""" Notes:
        1.  Include a trailing slash at the end of the directory path
            ("Method 1," below).
        2.  If a subdirectory in your intended path matches an existing file
            with same name, you will get the following error:
            "NotADirectoryError: [Errno 20] Not a directory:" ...
"""
# Uncomment and try each of these "out_dir" paths, singly:

# ----------------------------------------------------------------------------
# METHOD 1:
# Re-running does not overwrite existing directories and files; no errors.

# out_dir = 'output/corpus3'                ## no error but no dir created (missing tailing /)
# out_dir = 'output/corpus3/'               ## works
# out_dir = 'output/corpus3/doc1'           ## no error but no dir created (missing tailing /)
# out_dir = 'output/corpus3/doc1/'          ## works
# out_dir = 'output/corpus3/doc1/doc.txt'   ## no error but no file created (os.makedirs creates dir, not files!  ;-)
# out_dir = 'output/corpus2/tfidf/'         ## fails with "Errno 20" (existing file named "corpus2")
# out_dir = 'output/corpus3/tfidf/'         ## works
# out_dir = 'output/corpus3/a/b/c/d/'       ## works

# [2] https://docs.python.org/3/library/os.html#os.makedirs

# Uncomment these to run "Method 1":

#directory = os.path.dirname(out_dir)
#os.makedirs(directory, mode=0o777, exist_ok=True)

# ----------------------------------------------------------------------------
# METHOD 2:
# Re-running does not overwrite existing directories and files; no errors.

# out_dir = 'output/corpus3'                ## works
# out_dir = 'output/corpus3/'               ## works
# out_dir = 'output/corpus3/doc1'           ## works
# out_dir = 'output/corpus3/doc1/'          ## works
# out_dir = 'output/corpus3/doc1/doc.txt'   ## no error but creates a .../doc.txt./ dir
# out_dir = 'output/corpus2/tfidf/'         ## fails with "Errno 20" (existing file named "corpus2")
# out_dir = 'output/corpus3/tfidf/'         ## works
# out_dir = 'output/corpus3/a/b/c/d/'       ## works

# Uncomment these to run "Method 2":

#import os, errno
#try:
#       os.makedirs(out_dir)
#except OSError as e:
#       if e.errno != errno.EEXIST:
#               raise
# ----------------------------------------------------------------------------
结论:在我看来,方法2更稳健

[1]


[2]

使用此命令检查并创建目录

 if not os.path.isdir(test_img_dir):
     os.mkdir(test_img_dir)
在程序/项目的入口点调用函数create_dir

import os

def create_dir(directory):
    if not os.path.exists(directory):
        print('Creating Directory '+directory)
        os.makedirs(directory)

create_dir('Project directory')

如果在支持命令的计算机上运行,为什么不使用子流程模块 带有-p选项的mkdir? 适用于Python2.7和Python3.6

from subprocess import call
call(['mkdir', '-p', 'path1/path2/path3'])
在大多数系统上都应该这样做

在可移植性无关紧要的情况下,使用docker的解决方案是干净的2行。您也不必添加逻辑来检查目录是否存在。最后,重新运行是安全的,没有任何副作用

如果需要错误处理:

from subprocess import check_call
try:
    check_call(['mkdir', '-p', 'path1/path2/path3'])
except:
    handle...

在创建目录之前,必须设置完整路径:

if not os.path.exists(d):
    os.makedirs(d)
import os,sys,inspect
import pathlib

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
your_folder = currentdir + "/" + "your_folder"

if not os.path.exists(your_folder):
   pathlib.Path(your_folder).mkdir(parents=True, exist_ok=True)

这对我很有用,希望它也能对您有用。在Linux下,您可以在一行中创建目录:

import os
os.system("mkdir -p {0}".format('mydir'))

您可以在一个命令中创建一个文件及其所有父目录,该命令的fastcore扩展名为pathlib:path.mk_writedata

从fastcore.utils导入路径 路径'/dir/to/file.txt'.mk_写'Hello World'
我本想对这个问题发表评论,但我们是说os.mkdir吗?我的python 2.5.2没有os.path.mkdir…没有os.path.mkdir方法。模块在路径名上实现了一些有用的函数。使用try/except,当目录不存在但由于某种原因无法生成时,您将在创建目录时屏蔽错误。如果路径是现有文件或目录,则将在此处引发ItoError。我已经发布了一个答案来解决这个问题。这已经完成了一半。在决定忽略它之前,您确实需要检查OSError的子错误条件。请参阅。竞争条件是一个很好的点,但中的方法将掩盖创建目录的失败。不要因为投票被否决而感到难过——你不喜欢这个答案。这就是投票的目的。记住os.path.exists不是免费的。如果正常情况下目录将在那里,那么不在那里的情况应作为异常处理。换句话说,尝试打开并写入文件,捕获OSError异常,并基于errno执行makedir,然后重试或重新引发。这将创建代码的重复,除非将写入内容包装在本地方法中。os.path.exists也会为文件返回True。我已经发布了一个答案来解决这个问题。正如其他答案的评论者所指出的,os.makedirs的exists_ok参数可用于说明如何处理之前存在的路径,因为Python 3.2.os.mkdirs可能会创建意外的文件夹,如果路径分隔符意外遗漏,则当前文件夹不是预期的,路径元素包含路径分隔符。如果您使用os.mkdir,这些错误将引发异常,提醒您它们的存在。两个问题:1您需要在决定检查os.path.exists之前检查OSError的子错误条件-请参阅stackoverflow.com/a/5032238/763269,2在os.path.exists上成功并不意味着该目录存在,只要路径存在,就可以是文件、符号链接或其他文件系统

通常,您可能需要考虑文件名中没有目录的情况。在我的机器上,dirname'foo.txt'gives不存在并导致makedir失败。在python 2.7中,os.path.mkdir不存在。是的。如果路径存在,不仅要检查它是否是一个目录,而不是一个常规文件或另一个对象许多答案都要检查它是否可写我没有找到一个答案来检查这个如果你来这里创建文件路径字符串p的父目录,这是我的代码片段:os.makedirsp[:p.rindexos.path.sep],exist_ok=true被接受的答案实际上是危险的,因为它有一个竞态条件。但是,它更简单,因此如果您不知道竞态条件,或者认为它不适用于您,这将是您明显的第一选择。只有当exception.errno!=errno.EEXIST存在路径但是非目录对象,如文件。如果路径是非目录对象,则理想情况下应引发异常。请注意,上述代码等效于os.makedirspath,exist\u ok=True@Navinexist_ok参数是在Python3.2中引入的。它在Python2.x中不存在。我将把它合并到我的答案中。@HeikkiToivonen Technicall我的意思是,如果另一个程序同时修改目录和文件,那么你的整个程序就是一个巨大的竞争条件。如何阻止另一个程序在代码创建目录之后,在你实际将文件放入目录之前删除它呢?这个答案尽我所能涵盖了几乎所有的特殊情况告诉你。我计划用if not os.path.isdir来包装它,因为我希望目录几乎每次都存在,我可以通过这种方式避免异常。@CharlesL。如果你的原因是性能,异常可能比检查的磁盘IO便宜。@jpmc26但是makedirs在只检查抛出时做额外的stat、umask、lstatOSError。这是错误的答案,因为它引入了一个潜在的FS race cond。请参阅Aaron Hall的答案。正如@sleepycal所说,这与已接受的答案存在类似的竞争条件。如果在引发错误和检查os.path.isdir之间,其他人删除了该文件夹,您将引发错误、过时和令人困惑的错误er存在。如果您仅使用“isdir”,当您尝试创建目录且已存在同名文件时,您是否仍会遇到问题?@mr在现有文件上创建目录时产生的异常将正确地将问题反映回调用方。distutils.dir_util不是distutil公用程序的一部分PI和在多线程环境中存在问题:是的。正如bug的第二部分中所指出的,distutils.dir_util.mkpath的问题是,如果您创建一个目录,然后从Python内部或外部删除它,然后再次使用mkpath,mkpath将只使用其先前创建该目录的无效缓存信息,而不会实际生成该目录与此相反,os.makedirs不依赖任何此类缓存。新的IPython文档。IPython模块绝对不能保证存在。它本机存在于我的Mac上,但不存在于我的任何Linux安装的Python上。基本上,它不是.Sure中列出的模块之一。要安装此包,只需运行通常的pip install ipython或将依赖项包含在requirements.txt或pom.xml中。文档:@JanuszSkonieczny是较新的后端口。较旧的后端口未维护。如自述文件第1行所述;P。但旧的后端口仍然适用于此处的答案。并且没有命名问题。无需解释原因对于新用户,什么时候使用pathlib,在什么地方使用pathlib2,我认为这里的专业人士会找出不推荐的地方;这并没有回答这个问题,这如何回答创建目录的问题?最好使用独立于操作系统的方法。
# Create a directory and any missing ancestor directories. 
# If the directory already exists, do nothing.

from distutils.dir_util import mkpath
mkpath("test")    
os.path.isdir('/tmp/dirname')
from pathlib import Path
path = Path('/my/directory/filename.txt')
path.parent.mkdir(parents=True, exist_ok=True) 
# path.parent ~ os.path.dirname(path)
os.makedirs(path,exist_ok=True)
import os
import errno

def make_sure_path_exists(path):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise
import os
if os.path.isfile(filename):
    print "file exists"
else:
    "Your code here"
└── output/         ## dir
   ├── corpus       ## file
   ├── corpus2/     ## dir
   └── subdir/      ## dir
# ----------------------------------------------------------------------------
# [1] https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist

import pathlib

""" Notes:
        1.  Include a trailing slash at the end of the directory path
            ("Method 1," below).
        2.  If a subdirectory in your intended path matches an existing file
            with same name, you will get the following error:
            "NotADirectoryError: [Errno 20] Not a directory:" ...
"""
# Uncomment and try each of these "out_dir" paths, singly:

# ----------------------------------------------------------------------------
# METHOD 1:
# Re-running does not overwrite existing directories and files; no errors.

# out_dir = 'output/corpus3'                ## no error but no dir created (missing tailing /)
# out_dir = 'output/corpus3/'               ## works
# out_dir = 'output/corpus3/doc1'           ## no error but no dir created (missing tailing /)
# out_dir = 'output/corpus3/doc1/'          ## works
# out_dir = 'output/corpus3/doc1/doc.txt'   ## no error but no file created (os.makedirs creates dir, not files!  ;-)
# out_dir = 'output/corpus2/tfidf/'         ## fails with "Errno 20" (existing file named "corpus2")
# out_dir = 'output/corpus3/tfidf/'         ## works
# out_dir = 'output/corpus3/a/b/c/d/'       ## works

# [2] https://docs.python.org/3/library/os.html#os.makedirs

# Uncomment these to run "Method 1":

#directory = os.path.dirname(out_dir)
#os.makedirs(directory, mode=0o777, exist_ok=True)

# ----------------------------------------------------------------------------
# METHOD 2:
# Re-running does not overwrite existing directories and files; no errors.

# out_dir = 'output/corpus3'                ## works
# out_dir = 'output/corpus3/'               ## works
# out_dir = 'output/corpus3/doc1'           ## works
# out_dir = 'output/corpus3/doc1/'          ## works
# out_dir = 'output/corpus3/doc1/doc.txt'   ## no error but creates a .../doc.txt./ dir
# out_dir = 'output/corpus2/tfidf/'         ## fails with "Errno 20" (existing file named "corpus2")
# out_dir = 'output/corpus3/tfidf/'         ## works
# out_dir = 'output/corpus3/a/b/c/d/'       ## works

# Uncomment these to run "Method 2":

#import os, errno
#try:
#       os.makedirs(out_dir)
#except OSError as e:
#       if e.errno != errno.EEXIST:
#               raise
# ----------------------------------------------------------------------------
 if not os.path.isdir(test_img_dir):
     os.mkdir(test_img_dir)
import os

def create_dir(directory):
    if not os.path.exists(directory):
        print('Creating Directory '+directory)
        os.makedirs(directory)

create_dir('Project directory')
from subprocess import call
call(['mkdir', '-p', 'path1/path2/path3'])
from subprocess import check_call
try:
    check_call(['mkdir', '-p', 'path1/path2/path3'])
except:
    handle...
import os,sys,inspect
import pathlib

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
your_folder = currentdir + "/" + "your_folder"

if not os.path.exists(your_folder):
   pathlib.Path(your_folder).mkdir(parents=True, exist_ok=True)
import os
os.system("mkdir -p {0}".format('mydir'))