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

1598 投票
15 回答
1585442 浏览
提问于 2025-04-17 10:39

我怎么在Python中检查一个文件夹是否存在呢?

15 个回答

95

快到了!os.path.isdir 这个函数会检查你给它的名字是不是一个存在的文件夹。如果这个文件夹存在,它就会返回 True;如果这个文件夹不存在或者你给的名字不是一个文件夹,它就会返回 False

126

Python 3.4 版本引入了一个叫做 `pathlib` 模块,这个模块让我们可以用面向对象的方式来处理文件系统的路径。你可以使用 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。

2324

使用 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

撰写回答