如何检查目录是否存在?


当前回答

如:

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

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

其他回答

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

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

>>> 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
#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.isdir(路径)