Python判断文件-目录存在的方法.doc
《Python判断文件-目录存在的方法.doc》由会员分享,可在线阅读,更多相关《Python判断文件-目录存在的方法.doc(1页珍藏版)》请在三一文库上搜索。
1、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异常。如果文件无操作权限,则会抛出Pers
2、missionError异常。filePath = /path/to/filetry: file = open(filePath) file.close()except FileNotFoundError: print(No such file or directory: %s % filePath)except IsADirectoryError: print(Is a directory: %s % filePath)except PermissionError: print(Permission denied: %s % filePath)else: print(File is exist: %s % filePath)使用 pathlib 模块import pathlibpath = pathlib.Path(path/to/file)# 判断路径是否存在path.exists()# 判断是否为文件path.is_file()# 判断是否为目录path.is_dir()
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Python 判断 文件 目录 存在 方法
链接地址:https://www.31doc.com/p-3271900.html