如何检查目录是否存在?


当前回答

仅对目录使用os.path.isdir:

>>> import os
>>> os.path.isdir('new_folder')
True

对文件和目录使用os.path.exists:

>>> import os
>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
False

或者,您可以使用pathlib:

 >>> from pathlib import Path
 >>> Path('new_folder').is_dir()
 True
 >>> (Path.cwd() / 'new_folder' / 'file.txt').exists()
 False

其他回答

是的,使用os.path.exists()。

以下代码检查代码中引用的目录是否存在,如果您的工作场所中不存在,则会创建一个:

import os

if not os.path.isdir("directory_name"):
    os.mkdir("directory_name")

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

os.path.isdir("directory")

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

os.path.exists("directoryorfile")

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

检查路径是否为目录;

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

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

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

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将抛出异常。