Python 判断文件或目录是否存在的实例代码
作者:Shocker 时间:2021-08-16 14:44:49
使用 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()
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 pathlib
path = pathlib.Path('path/to/file')
# 判断路径是否存在
path.exists()
# 判断是否为文件
path.is_file()
# 判断是否为目录
path.is_dir()
总结
以上所述是小编给大家介绍的Python 判断文件或目录是否存在的实例代码网站的支持!
来源:https://www.cnblogs.com/shockerli/archive/2018/07/19/python-determine-file-exist.html
标签:python,判断,文件,目录
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python线程的几种创建方式详解
2023-06-11 20:23:35
python 实现的截屏工具
2023-05-15 00:20:39
![](https://img.aspxhome.com/file/2023/5/86215_0s.png)
python中子类与父类的关系基础知识点
2022-11-26 23:45:12
如何解决SQLServer占内存过多的问题
2008-12-18 15:01:00
python 处理数字,把大于上限的数字置零实现方法
2022-11-13 09:20:56
matplotlib bar()实现百分比堆积柱状图
2022-06-22 02:05:22
![](https://img.aspxhome.com/file/2023/8/87668_0s.png)
Python IDE Pycharm中的快捷键列表用法
2022-12-12 19:21:12
![](https://img.aspxhome.com/file/2023/5/86615_0s.png)
Pycharm及python安装详细教程(图解)
2023-01-06 00:26:00
![](https://img.aspxhome.com/file/2023/6/75266_0s.jpg)
深入了解Django中间件及其方法
2022-04-22 09:19:10
![](https://img.aspxhome.com/file/2023/0/70690_0s.jpg)
python绘制已知点的坐标的直线实例
2023-03-12 08:36:11
Go流程控制代码详解
2023-09-01 10:21:12
浅谈python requests 的put, post 请求参数的问题
2023-05-06 14:54:47
![](https://img.aspxhome.com/file/2023/1/101651_0s.jpg)
用文本+ASP打造新闻发布系统
2009-02-02 09:31:00
python切片作为占位符使用实例讲解
2023-10-13 09:26:50
使用Python的networkx绘制精美网络图教程
2022-10-31 06:52:47
![](https://img.aspxhome.com/file/2023/1/83911_0s.jpg)
python使用turtle库绘制树
2022-04-14 09:09:06
python 如何读、写、解析CSV文件
2022-09-21 13:59:33
![](https://img.aspxhome.com/file/2023/7/97627_0s.jpg)
Django框架静态文件使用/中间件/禁用ip功能实例详解
2023-06-12 02:48:38
![](https://img.aspxhome.com/file/2023/6/71346_0s.png)
asp.net中文件下载功能的实例代码
2023-07-20 15:46:51
react redux及redux持久化示例详解
2023-07-17 07:18:53
![](https://img.aspxhome.com/file/2023/7/55977_0s.png)