判断文件是否存在

undefined·2022-06-25 20:36·218 次阅读

判断文件是否存在

一、判断文件

1、判断存在

判断文件是否存在

Copy
#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 '''

判断文件夹是否存在

Copy
#文件夹是否存在 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()

Copy
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、判读写

判断文件是否可读写

Copy
#判断是否可读写 #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")

二、异常捕捉

Copy
try: pass except: pass
Copy
#异常捕捉 #文件不存在,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.")
posted @   Saint_Z  阅读(218)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示