如果你提供的路径不存在,许多 Python 函数就会崩溃并报错。os.path 模块提供了一些函数,用于检测给定的路径是否存在,以及它是文件还是文件夹。
• 如果 path 参数所指的文件或文件夹存在,调用 os.path.exists(path)将返回 True,否则返回 False。
• 如果 path 参数存在,并且是一个文件,调用 os.path.isfile(path)将返回 True,否则返回 False。
• 如果 path 参数存在,并且是一个文件夹,调用 os.path.isdir(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 计算机上,我想用卷名 D:\检查一个闪存盘,可以这样做:
>>> os.path.exists('D:\\')
False
不好!看起来我忘记插入闪存盘了。