import os
# 使用Try语句捕获异常
try:
f =open(r'E:\\PyCharmWorkSpace\\interfaceTest\\testFile\\哈123.xls') #可直接使用open()方法来检查文件是否存在和可读写,当然其他方法也可以
f.close()
print("success")
except FileNotFoundError:
print("File is not found.") # 文件不存在
except PermissionError:
print("You don't have permission to access this file.") # 文件存在无权限访问
# os.access(path, mode) path为文件路径,mode为操作模式,有这么几种:
# os.F_OK: 检查文件是否存在;os.R_OK: 检查文件是否可读;os.W_OK: 检查文件是否可以写入;os.X_OK: 检查文件是否可以执行
if(os.access(r'E:\\PyCharmWorkSpace\\interfaceTest\\testFile\\哈123.xls',os.F_OK)):
print("文件存在")
else:
print("文件不存在")