python中如何避免格式敏感导致的错误以及EXCEPT未匹配TRY的错误

以下代码中又两个错误:

#读取TXT文档

filetemp = codecs.open('C:/Users/****/Desktop/test7.txt', mode='r', encoding='utf-8')  # 打开txt文件,以‘utf-8’编码读取
except FileNotFoundError: #如果文件不存在,给提示
    print("file is not found")

错误一:python对格式敏感,第一行因为头部没有TAB缩进,导致提示错误;

错误二:except不能单独出现,必须在前部写try来配对;

修订的代码如下:

#读取TXT文档
try:
    filetemp = codecs.open('C:/Users/****/Desktop/test7.txt', mode='r', encoding='utf-8')  # 打开txt文件,以‘utf-8’编码读取
except FileNotFoundError: #如果文件不存在,给提示
    print("file is not found")
发布了51 篇原创文章 · 获赞 20 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/xuexijiaoliu/article/details/100798914
今日推荐