Python 3基础教程25-异常处理
在Python中,异常处理,主要是try except语句,通常语法格式如下.
try:
代码块1
except Exception as e:
print(e)
代码2
接着前面读取CSV文件,如果我们csv文件不存在,针对这个写一个异常处理。
1 import csv 2 3 try: 4 with open(r'C:\Users\Anthony\Desktop\example1.csv') as csvfile: 5 readCSV = csv.reader(csvfile, delimiter=',') 6 citys = [] 7 password = [] 8 days = [] 9 for row in readCSV: 10 city = row[0] 11 paword = row[1] 12 day = row[2] 13 14 citys.append(city) 15 password.append(paword) 16 days.append(day) 17 18 print(citys) 19 print(password) 20 print(days) 21 except Exception as e: 22 print(e) 23 print('请确认该csv文件是否存在或路径是否写对!')
上面的exceple1.csv文件在桌面是不存在的,运行结果
[Errno 2] No such file or directory: 'C:\\Users\\Anthony\\Desktop\\example1.csv'
请确认该csv文件是否存在或路径是否写对!
>>>