我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。

也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?


当前回答

在Python中做到这一点的最佳方法

#Devil
import os
directory = "./out_dir/subdir1/subdir2"
if not os.path.exists(directory):
    os.makedirs(directory)

其他回答

我下载了下面的文章,但这不是完全愚蠢的。

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

如今,正如我所说的那样,这不是真正的愚蠢,因为我们有可能无法在那个时期创建目录,还有另一个创建过程。

在 Python ≥ 3.5 上使用 pathlib.Path.mkdir:

from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)

对于旧版本的Python,我看到两个答案有良好的品质,每一个有一个小错误,所以我会给我的答案:

import os
if not os.path.exists(directory):
    os.makedirs(directory)

正如评论和其他地方所指出的那样,有一个赛事状态 - 如果目录在 os.path.exists 和 os.makedirs 呼叫之间创建, os.makedirs 会失败 OSError. 不幸的是,包装捕捉 OSError 和继续不是虚假的,因为它会忽略由于其他因素创建目录的失败,如不够的许可,完整的磁盘等。

import os, errno

try:
    os.makedirs(directory)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise

否则,可能有第二个 os.path.exists,但假设另一个创建了目录后第一次检查,然后删除它之前的第二个 - 我们仍然可以被误导。

现代版本的Python改进这个代码相当一点,两者都通过曝光FileExistsError(在3.3+)。

try:
    os.makedirs("path/to/directory")
except FileExistsError:
    # directory already exists
    pass

...和允许一个关键词论点给os.makedirs称为 exist_ok(在3.2+)。

os.makedirs("path/to/directory", exist_ok=True)  # succeeds even if directory exists.

在 Python3 中,OS.makedirs 支持设置 exist_ok. 默认设置是 False,这意味着如果目标目录已经存在,则将升级到 OSError. 通过设置 exist_ok 到 True,则将被忽略到 OSError(目录存在)并不会创建目录。

os.makedirs(path,exist_ok=True)

在 Python2 中, os.makedirs 不支持 exist_ok 设置. 在 heikki-toivonen 的答案中,您可以使用方法:

import os
import errno

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

使用尝试除外,并从 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' 并从中删除所有权限,您将获得一个 OSError 提取的 errno.EACCES (Permission denied, error 13)。

我找到了这个Q/A之后我被一些失败和错误我得到,当我在Python的目录工作,我在Python 3工作(在一个Anaconda虚拟环境中的3.5在一个Arch Linux x86_64系统)。

考虑此目录结构:

└── 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] https://docs.python.org/3/图书馆/os.html#os.makedirs