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

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


当前回答

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)

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


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

其他回答

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

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

在您的程序/项目的输入点上拨打 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')

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

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)

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


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