python怎么检查文件是否存在
python检查文件是否存在的方法:
os模块中的os.path.exists(path)可以检测文件或文件夹是否存在,path为文件/文件夹的名字/绝对路径。返回结果为True/False
printos.path.exists("/untitled/chapter3.py")printos.path.exists("chapter3.py")
这种用法既能检测文件也能检测文件夹,这也带来问题,假如我想找一个命名为helloworld的文件,使用exists可能命中同名的helloworld文件夹。这时使用os.path.isdir()和os.path.isfile()可以加以区分。如果进一步想判断是否可以操作文件,可以使用os.access(path,model),model为操作模式,具体如下
if__name__=='__main__':
ifos.access("/untitled/chapter3.py",os.F_OK):
print"Filepathisexist."
ifos.access("/untitled/chapter3.py",os.R_OK):
print"Fileisaccessibletoread"
ifos.access("/untitled/chapter3.py",os.W_OK):
print"Fileisaccessibletowrite"
ifos.access("/untitled/chapter3.py",os.X_OK):
print"Fileisaccessibletoexecute"
try语句
对文件最简单的操作方法是直接使用open()方法,但是文件不存在,或发生权限问题时open方法会报错,所以配合try语句使用来捕捉一异常。try...open语法简单优雅,可读性强,而且不需要引入任何模块
if__name__=='__main__':
try:
f=open("/untitled/chapter3.py")
f.close()
exceptIOError:
print"Fileisnotaccessible."
pathlib模块
在python2中pathlib属于第三方模块,需要单独安装。但是python3中pathlib已经是内建模块了
pathlib用法简单,与open类似。首先使用pathlib创建对象,进而使用exists(),is_file()等方法
if__name__=='__main__':
path=pathlib.Path("chapter3.py")
printpath.exists()
printpath.is_file()
以上内容为大家介绍了python培训之怎么检查文件是否存在,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python字典中添加新的键值
python字典中添加新的键值1、字典是动态结构,可以随时添加新的元素。如在字典中添加bullet子弹的x和y坐标。print(bullet)可以看到字典中有了bu...详情>>
2023-11-10 15:45:55
pythonDecimal解决计算问题
pythonDecimal解决计算问题1、当python中的浮点类型计算出现不准确结果时,Decimal用于纠正。经验证,Decimal不直接处理浮点类型数据,而是将浮...详情>>
2023-11-10 14:43:40
python静态方法的用法
python静态方法的用法1、通过装饰器@staticmethod定义静态方法。2、@staticmethod必须写在方法上。3、在静态方法中访问实例属性和实例方法会导...详情>>
2023-11-10 14:02:20
python新手如何系统学习
我们可把学习python分为4个阶段,每个阶段需要完善的掌握知识点,python最初是作为管理linux系统而出生的,python的环境部署最好在linux上面,...详情>>
2023-11-10 13:37:42