如何检查目录是否存在?


当前回答

太近了!如果传入当前存在的目录名,os.path.isdir将返回True。如果它不存在或不是目录,则返回False。

其他回答

#You can also check it get help for you

if not os.path.isdir('mydir'):
    print('new directry has been created')
    os.system('mkdir mydir')

os为您提供了许多这些功能:

import os
os.path.isdir(dir_in) #True/False: check if this is a directory
os.listdir(dir_in)    #gets you a list of all files and directories under dir_in

如果输入路径无效,listdir将抛出异常。

有一个方便的Unipath模块。

>>> from unipath import Path 
>>>  
>>> Path('/var/log').exists()
True
>>> Path('/var/log').isdir()
True

您可能需要的其他相关事项:

>>> Path('/var/log/system.log').parent
Path('/var/log')
>>> Path('/var/log/system.log').ancestor(2)
Path('/var')
>>> Path('/var/log/system.log').listdir()
[Path('/var/foo'), Path('/var/bar')]
>>> (Path('/var/log') + '/system.log').isfile()
True

您可以使用pip安装它:

$ pip3 install unipath

它类似于内置的pathlib。不同之处在于,它将每个路径都视为字符串(path是str的子类),因此如果某个函数需要字符串,则可以轻松地将其传递给path对象,而无需将其转换为字符串。

例如,这对Django和settings.py非常有用:

# settings.py
BASE_DIR = Path(__file__).ancestor(2)
STATIC_ROOT = BASE_DIR + '/tmp/static'

如果目录不在,您可能还想创建该目录。

来源,如果它还在SO上。

=====================================================================

在Python≥3.5时,使用pathlib.Path.mkdir:

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

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

尝试os.path.exists,并考虑创建os.makedirs。

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

正如注释和其他地方所指出的,存在一个竞争条件——如果在os.path.exists和os.makedirs调用之间创建目录,os.makedir将失败,并出现OSError。不幸的是,全面捕获OSError并继续并不是万无一失的,因为它会忽略由于其他因素(如权限不足、磁盘已满等)导致的目录创建失败。

一种选择是捕获OSError并检查嵌入的错误代码(请参阅是否有跨平台的方式从Python的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.

我们可以检查2个内置函数

os.path.isdir("directory")

如果指定的目录可用,它将为布尔值true。

os.path.exists("directoryorfile")

如果指定的目录或文件可用,它将为boolead true。

检查路径是否为目录;

os.path.isdir(“目录路径”)

如果路径为directory,则返回布尔值true