如何检查目录是否存在?
当前回答
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。
仅提供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
有一个方便的Unipath模块。
>>> from unipath import Path
>>>
>>> Path('/var/log').exists()
True
>>> Path('/var/log').isdir()
True
您可能需要的其他相关事项:
>>> Path('/var/log/system.log').parent
Path('/var/log')
>>> Path('/var/log/system.log').ancestor(2)
Path('/var')
>>> Path('/var/log/system.log').listdir()
[Path('/var/foo'), Path('/var/bar')]
>>> (Path('/var/log') + '/system.log').isfile()
True
您可以使用pip安装它:
$ pip3 install unipath
它类似于内置的pathlib。不同之处在于,它将每个路径都视为字符串(path是str的子类),因此如果某个函数需要字符串,则可以轻松地将其传递给path对象,而无需将其转换为字符串。
例如,这对Django和settings.py非常有用:
# settings.py
BASE_DIR = Path(__file__).ancestor(2)
STATIC_ROOT = BASE_DIR + '/tmp/static'
#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.exists()。
推荐文章
- 在python中,年龄从出生日期开始
- 使用pip安装SciPy
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?
- 在Python中,冒号等于(:=)是什么意思?
- Python "SyntaxError:文件中的非ascii字符'\xe2' "
- 如何从psycopg2游标获得列名列表?
- Python中dict对象的联合
- 如何有效地比较两个无序列表(不是集合)?