在Python3的文件操作中,我们经常会遇到需要检查文件是否存在的情况,因为只有文件存在,才可以进行下一步的处理。那么Python3中如何检查文件是否存在?常用的方法主要有两种,本文为大家详细介绍一下。
一、 使用os库
os库方法可检查文件是否存在,存在返回Ture,不存在返回False,且不需要打开文件。
1. os.path.isfile文件检查
import os.path filename='/oldboyedu.com/file.txt' os.path.isfile(filename)
2. os.path.exists文件夹检查
import os a_path='/oldboyedu.com/' if os.path.exists(a_path): #do something
3. os.access文件权限检查
import os filename='/oldboyedu.com/file.txt' if os.path.isfile(filename) and os.access(filename, os.R_OK): #do something
二、使用pathlib库
使用pathlib库也是一种检查文件是否存在的方法,且从Python3.4开始,Python已经把pathlib加入了标准库,无需安装,即可直接使用!
1. 检查文件是否存在
from pathlib import Path my_file = Path("/oldboyedu.com/file.txt") if my_file.is_file(): # file exists
2. 检查文件夹是否存在
from pathlib import Path my_file = Path("/oldboyedu.com/file.txt") if my_file.is_dir(): # directory exists
3. 文件或文件夹是否存在
from pathlib import Path my_file = Path("/oldboyedu.com/file.txt") if my_file.exists(): # path exists
想要学习Python,却又担心找不到合适的Python培训机构,在这里推荐大家来老男孩教育。老男孩教育师资团队强大、从业经验丰富、课程体系完善,且拥有真实企业级实战项目,欢迎大家前来试听。
联系我时请说明是在起航培训网看到的,谢谢!
注意:起航培训网只是架起培训机构与学员之间的一道桥梁,帮助培训机构找学员,帮助学员找培训机构的平台,不产生金钱交易,如果你有资金往来,请及时通过电话与对方联系,调查清楚,确认无误在选择,否则造成你的损失,由自己承担,本平台概不负责,谢谢!




未上传身份证认证
未上传办学许可认证 