Python 判断文件或目录是否存在的实例代码
使用os模块
判断文件是否存在
os.path.isfile(path)
判断目录是否存在
os.path.isdir(path)
判断路径是否存在
#使用path模块 os.path.exists(path) #使用access()方法 os.access(path,os.F_OK)
使用open函数和异常捕获
如果直接用open()函数打开一个不存在的文件时,程序会抛出异常,我们可以通过try语句来捕获异常以达到判断文件是否存在的目的。
如果文件不存在,open()函数会抛出FileNotFoundError异常。如果文件无操作权限,则会抛出PersmissionError异常。
filePath='/path/to/file' try: file=open(filePath) file.close() exceptFileNotFoundError: print("Nosuchfileordirectory:'%s'"%filePath) exceptIsADirectoryError: print("Isadirectory:'%s'"%filePath) exceptPermissionError: print("Permissiondenied:'%s'"%filePath) else: print("Fileisexist:'%s'"%filePath)
使用pathlib模块
importpathlib path=pathlib.Path('path/to/file') #判断路径是否存在 path.exists() #判断是否为文件 path.is_file() #判断是否为目录 path.is_dir()
总结
以上所述是小编给大家介绍的Python判断文件或目录是否存在的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!