如何检查目录是否存在?


当前回答

#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.path.exists()。

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

仅提供os.stat版本(python 2):

import os, stat, errno
def CheckIsDir(directory):
  try:
    return stat.S_ISDIR(os.stat(directory).st_mode)
  except OSError, e:
    if e.errno == errno.ENOENT:
      return False
    raise

是,使用os.path.isdir(路径)

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

os.path.isdir("directory")

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

os.path.exists("directoryorfile")

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

检查路径是否为目录;

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

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