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

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


当前回答

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

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

其他回答

你可以使用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。

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

我看到了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

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

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