如果你提供的路径不存在,许多 Python 函数就会崩溃并报错。os.path 模块提供了一些函数,用于检测给定的路径是否存在以及它是文件还是文件夹。 | |
| |
| |
| path参数存在,并且是一个文件夹返回True,否则返回False |
代码示例与讲解
#代码 os.path.exists('C:\\Windows') #运行输出结果:True
#代码 os.path.exists('C:\\some_made_up_folder') #运行输出结果:False
#代码 os.path.isdir('C:\\Windows\\System32') #运行输出结果:True
#代码 os.path.isfile('C:\\Windows\\System32') #运行输出结果:False
#代码 os.path.isdir('C:\\Windows\\System32\\calc.exe') #运行输出结果:False
#代码 os.path.isfile('C:\\Windows\\System32\\calc.exe') #运行输出结果:True
利用os.path.exists()函数,可以确定DVD或闪存盘当前是否连在计算机上。例如,如果在Windows计算机上,我想检查一个名为F:\的盘是否存在,可以这样做:
#代码 os.path.exists('F:\\')#运行输出结果:False,这是因为电脑上没有F盘或者未插入识别为F盘的U盘,如果有的话就是True