如何检查目录是否存在?


当前回答

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

os.path.isdir("directory")

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

os.path.exists("directoryorfile")

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

检查路径是否为目录;

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

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

其他回答

仅提供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。

有一个方便的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'
#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')

如:

In [3]: os.path.exists('/d/temp')
Out[3]: True

很可能会在一条os.path.isdir(…)中抛出。