如何检查目录是否存在?


当前回答

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

其他回答

仅提供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将返回True。如果它不存在或不是目录,则返回False。

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

os.path.isdir("directory")

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

os.path.exists("directoryorfile")

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

检查路径是否为目录;

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

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

#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')

Python 3.4在标准库中引入了pathlib模块,它提供了一种面向对象的方法来处理文件系统路径。Path对象的is_dir()和exists()方法可用于回答以下问题:

In [1]: from pathlib import Path

In [2]: p = Path('/usr')

In [3]: p.exists()
Out[3]: True

In [4]: p.is_dir()
Out[4]: True

路径(和字符串)可以使用/运算符连接在一起:

In [5]: q = p / 'bin' / 'vim'

In [6]: q
Out[6]: PosixPath('/usr/bin/vim') 

In [7]: q.exists()
Out[7]: True

In [8]: q.is_dir()
Out[8]: False

Python 2.7上也可以通过PyPi上的pathlib2模块获得Pathlib。