如何检查目录是否存在?


当前回答

如:

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

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

其他回答

仅对目录使用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()。

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

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。

如:

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

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