判断文件是否存在
一、判断文件
1、判断存在
判断文件是否存在
#os.path.exists
a = os.path.exists('..\stock_deal\excel_data\stock_data2022-05-18.csv')
print(a)
b = os.path.exists('stock_data2022-05-18.csv')
print(b)
'''
True
False
'''
判断文件夹是否存在
#文件夹是否存在
print(os.path.exists('..\static'))
print(os.path.exists('.\static'))
print(os.path.exists('static'))
print(os.path.exists('..\de_py'))
print(os.path.exists('...\de_py'))
'''
False
True
True
True
False
'''
判断文件和文件夹存在都可以用os.path.exists(),存在同名问题,可以分别搜索文件.isfile()和文件夹.isdir()
print(os.path.exists('..\stock_deal\excel_data\stock_data2022-05-18'))
print(os.path.isfile('..\stock_deal\excel_data\stock_data2022-05-18.csv'))
print(os.path.isdir('.\static'))
2、判读写
判断文件是否可读写
#判断是否可读写
#os.F_OK: 检查文件是否存在
#os.R_OK: 检查文件是否可读
#os.W_OK: 检查文件是否可以写入
#os.X_OK: 检查文件是否可以执行
if os.access('..\stock_deal\excel_data\stock_data2022-05-18.csv', os.F_OK):
print("Given file path is exist.")
if os.access('..\stock_deal\excel_data\stock_data2022-05-18.csv', os.R_OK):
print("File is accessible to read")
if os.access('..\stock_deal\excel_data\stock_data2022-05-18.csv', os.W_OK):
print("File is accessible to write")
if os.access('..\stock_deal\excel_data\stock_data2022-05-18.csv', os.X_OK):
print("File is accessible to execute")
二、异常捕捉
try:
pass
except:
pass
#异常捕捉
#文件不存在,FileNotFoundError异常
#文件存在,但是没有权限访问,PersmissionError异常
try:
f =open('..\stock_deal\excel_data\stock_data2022-05-18.csv')
f.close()
except FileNotFoundError:
print("File is not found.")
except PermissionError:
print("You don't have permission to access this file.")
#上面两个异常都是IOError的子类。所以可以改成
#except IOError:
# print("File is not accessible.")
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?