13-检查路径的有效性
9.1.11 检查路径的有效性
如果你提供的路径不存在,许多Python函数就会崩溃并报错。好在 Path
对象有一些方法来检查给定的路径是否存在,以及它是文件还是文件夹。假设变量 p
包含 Path
对象,那么可以预期会出现以下情况。
- 如果该路径存在,调用
p.exists()
将返回True
;否则返回False
。 - 如果该路径存在,并且是一个文件,调用
p.is_file()
将返回True
;否则返回False
。 - 如果该路径存在,并且是一个文件夹,调用
p.is_dir()
将返回True
;否则返回False
。
在我的计算机上,下面是我在交互式环境中使用这些函数的结果:
>>> winDir = Path('C:/Windows')
>>> notExistsDir = Path('C:/This/Folder/Does/Not/Exist')
>>> calcFile = Path('C:/Windows
/System32/calc.exe')
>>> winDir.exists()
True
>>> winDir.is_dir()
True
>>> notExistsDir.exists()
False
>>> calcFile.is_file()
True
>>> calcFile.is_dir()
False
利用 exists()
方法来检查,可以确定DVD或闪存盘当前是否连在计算机上。例如,如果在Windows操作系统的计算机上,我想用名称D:\检查一个闪存盘,可以这样做:
>>> dDrive = Path('D:/')
>>> dDrive.exists()
False
结果为False,表示未插入闪存盘。
较老的 os.path
模块可以使用 os.path.exists(path)
、 os.path.isfile (path)
和 os.path.isdir(path)
函数来完成相同的任务,它们的行为与 Path
对象的函数类似。从Python 3.6开始,这些函数可以接收 Path
对象,也可以接收文件路径的字符串。