错误处理
输出错误:try:, except ... as ...: 看如下代码
# -*- coding:utf-8 -*-
try:file = open('x.txt','r')
except Exception as e:print(e)"""
[Errno 2] No such file or directory: 'x.txt'
"""
处理错误:会使用到循环语句。首先报错:没有这样的文件No such file or directory. 然后决定是否输入y, 输入y以后,系统就会新建一个文件(要用写入的类型),再次运行后,文件中就会写入ssss
# -*- coding:utf-8 -*-
try:file=open('x.txt','r+')
except Exception as e:print(e)response = input('do you want to create a new file:')if response=='y':file=open('x.txt','w')else:pass
else:file.write('ssss')file.close()
"""
[Errno 2] No such file or directory: 'eeee.txt'
do you want to create a new file:'y'
#再执行一次
ssss #eeee.txt中会写入'ssss'