如何检查Python中是否存在目录?

2022-09-05 00:55:26

如何检查目录是否存在?


答案 1

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

答案 2

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

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

Pathlib 也可以通过 PyPi 上的 pathlib2 模块在 Python 2.7 上使用。