艺赛旗 RPA9.0全新首发免费下载 点击下载
http://www.i-search.com.cn/index.html?from=line1
前言
在平时的项目中和平时练习中积累一下代码,在最近的帖子中与大家做一点分享,在算法和语法有啥问题或能进行优化,还请大家指出。
1.使用os模块
判断文件是否存在
os.path.isfile(path)
判断目录是否存在
os.path.isdir(path)
判断文件是否存在
使用 path 模块
os.path.exists(path)
使用 access() 方法
os.access(path, os.F_OK)
2.使用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