如何检查目录是否存在?
当前回答
我们可以检查2个内置函数
os.path.isdir("directory")
如果指定的目录可用,它将为布尔值true。
os.path.exists("directoryorfile")
如果指定的目录或文件可用,它将为boolead true。
检查路径是否为目录;
os.path.isdir(“目录路径”)
如果路径为directory,则返回布尔值true
其他回答
如:
In [3]: os.path.exists('/d/temp')
Out[3]: True
很可能会在一条os.path.isdir(…)中抛出。
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将抛出异常。
太近了!如果传入当前存在的目录名,os.path.isdir将返回True。如果它不存在或不是目录,则返回False。
#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.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
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录