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

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


试试 os.path.exist 函数

if not os.path.exists(dir):
    os.mkdir(dir)

查看 os.makedirs: (它确保完整的路径存在) 要处理可能存在的目录的事实,查找 OSError. (如果存在_ok 是假的(默认情况下),如果目标目录已经存在,则会升起 OSError。

import os
try:
    os.makedirs('./path/to/somewhere')
except OSError:
    pass

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

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

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()。

>>> os.path.exists('/tmp/dirname')
True
>>> os.path.exists('/tmp/dirname/filename.etc')
True
>>> os.path.isdir('/tmp/dirname/filename.etc')
False
>>> os.path.isdir('/tmp/fakedirname')
False

如果你有:

>>> directory = raw_input(":: ")

一个愚蠢的用户输入:

:: /tmp/dirname/filename.etc

... 您将以 filename.etc 命名的目录结束,当您将该论点转移到 os.makedirs(),如果您使用 os.path.exists()进行测试。

使用尝试除外,并从 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)。

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

pathlib.Path.mkdir 如上所述,重复创建目录,如果目录已经存在,则不会产生例外。

Python 3.2 以上:

使用Pathlib:

使用我们:

import os
os.makedirs(path, exist_ok=True)

使用Pathlib:

使用我们:

import os
try: 
    os.makedirs(path)
except OSError:
    if not os.path.isdir(path):
        raise

请注意,捕获例外和使用 errno 是有限的用途,因为 OSError: [Errno 17] 文件存在,即 errno.EEXIST,为文件和目录上传。

替代品:

import distutils.dir_util
distutils.dir_util.mkpath(path)

换句话说,如果您使用它创建一个目录,然后从内部或外部的目录删除,然后再使用目录重新创建相同的目录,目录将简单地沉默地使用其未成效的隐藏信息之前创建的目录,并将不起作用。


至于目录模式,请参考文档,如果您对此感兴趣。

相关的 Python 文档建议使用 EAFP 编码风格(更容易要求宽恕而不是允许)。

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 errno
try:
    os.makedirs(d)
except OSError as exception:
    if exception.errno != errno.EEXIST:
        raise

import tempfile

d = tempfile.mkdtemp()

有一个新的路径对象(如3.4)与许多方法,你会想使用路径 - 其中一个是 mkdir。

首先,相关进口:

from pathlib import Path
import tempfile

我们不需要处理 os.path.join 现在 - 只是加入路径部分与一个 /:

directory = Path(tempfile.gettempdir()) / 'sodata'

然后我无力地确保目录存在 - 存在_ok 论点在 Python 3.5 中出现:

directory.mkdir(exist_ok=True)

下面是文档的相关部分:

如果 exist_ok 是真实的,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))

路径对象必须在等待路径可以使用的其他API之前被强迫到Str。

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

关于这种情况的具体性

您在某个路径上提供一个特定的文件,然后从文件路径中提取目录,然后确保您有目录后,您试图打开阅读的文件。

import os
filepath = '/my/directory/filename.txt'
directory = os.path.dirname(filepath)

你的最终目标是打开这个文件,你最初表示,写作,但你基本上接近这个目标(基于你的代码),如此,打开文件阅读:

如果不是 os.path.exists(地址): os.makedirs(地址) f = 文件(文件名)

為什麼你會為你期望在那裡並能夠閱讀的檔案製作一個目錄?

只是试着打开文件。

with open(filepath) as my_file:
    do_stuff(my_file)

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模式(或一个添加)。

import os
if not os.path.exists(directory):
    os.makedirs(directory)
with open(filepath, 'w') as my_file:
    do_stuff(my_file)

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 中,您还可以使用全新 pathlib 模块:

from pathlib import Path
path = Path("/my/directory/filename.txt")
try:
    if not path.parent.exists():
        path.parent.mkdir(parents=True)
except OSError:
    # handle error; you can also catch specific errors like
    # FileExistsError and so on.

我看到了Heikki Toivonen和A-B-B的答案,并思考了这种变异。

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

对于单线解决方案,您可以使用 IPython.utils.path.ensure_dir_exists():

from IPython.utils.path import ensure_dir_exists
ensure_dir_exists(dir)

从文档:确保一个目录存在,如果它不存在,试着创建它,并保护它免受一个赛车状态,如果另一个过程正在做同样的事情。

IPython 是一个扩展包,而不是标准图书馆的一部分。

您可以使用 os.listdir 为此:

import os
if 'dirName' in os.listdir('parentFolderPath')
    print('Directory Exists')

你可以使用Megath。

# Create a directory and any missing ancestor directories. 
# If the directory already exists, do nothing.

from distutils.dir_util import mkpath
mkpath("test")    

请注意,它也将创建祖先目录。

它适用于Python 2和3。

如果你考虑下列事项:

os.path.isdir('/tmp/dirname')

这意味着一个目录(路径)存在,而且是一个目录,所以对我来说,这就是我所需要的,所以我可以确保它是文件夹(不是文件)并且存在。

从 Python 3.5 开始, pathlib.Path.mkdir 有一个 exist_ok 旗帜:

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 得到 exist_ok 旗帜从 python 3.2 e.g os.makedirs(路径, exist_ok=True))


注意:当我发表这个答案时,没有其他提到的答案存在_OK...

在 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

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

它鼓励用户输入目录,并且可以轻松修改。

我找到了这个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

使用此命令检查并创建 dir

 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')

为什么不使用子过程模块,如果运行支持命令 mkdir 的机器与 -p 选项? 在 Python 2.7 和 Python 3.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...

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

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)

这对我工作,我希望这对你也工作。

但我猜你的真正意图是创建一个文件和其主目录,因为它的内容全部在1命令。

您可以使用 fastcore 扩展到 pathlib: path.mk_write(数据)

from fastcore.utils import Path
Path('/dir/to/file.txt').mk_write('Hello World')

在Fastcore文档中查看更多

如果您正在写一个文件到一个变量路径,您可以在文件路径上使用此文件,以确保母目录创建。

from pathlib import Path

path_to_file = Path("zero/or/more/directories/file.ext")
parent_directory_of_file = path_to_file.parent
parent_directory_of_file.mkdir(parents=True, exist_ok=True)

工作,即使 path_to_file 是 file.ext (零目录深)。

查看 pathlib.PurePath.parent 和 pathlib.Path.mkdir。

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

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

最快的安全方式是:如果不存在,它会创造,如果不存在,它会消失:

from pathlib import Path
Path("path/with/childs/.../").mkdir(parents=True, exist_ok=True)