如何查找Python中是否存在目录

2024-04-26 05:51:00 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python的os模块中,有没有一种方法可以找到目录是否存在,比如:

>>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode
True/False

Tags: 模块path方法in目录falsetruenew
3条回答

如果您不关心它是文件还是目录,那么您将查找^{},或者^{}

示例:

import os
print(os.path.isdir("/home/el"))
print(os.path.exists("/home/el/myfile.txt"))

太近了!os.path.isdir如果传入当前存在的目录的名称,则返回True。如果它不存在或不是目录,则返回False

Python 3.4在标准库中引入了the ^{} module,它提供了一种面向对象的方法来处理文件系统路径:

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.exists()
Out[6]: True

In [7]: q.is_dir()
Out[7]: False

Pathlib也可以通过the pathlib2 module on PyPi.在Python 2.7上使用

相关问题 更多 >