![图片[1]-python怎么检查文件是否存在-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/5e8703373d3ac649.jpg)
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"
python学习网,免费的python学习网站,欢迎在线学习!
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已经是内建模块了
if__name__=='__main__':
path=pathlib.Path("chapter3.py")
printpath.exists()
printpath.is_file()原文来自:https://www.py.cn © 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END



















































暂无评论内容