美文网首页
python学习笔记(12月28日)-python异常

python学习笔记(12月28日)-python异常

作者: pency | 来源:发表于2016-12-28 21:21 被阅读0次

当电脑中没有a.txt这个文件时,

try:

f=open('a.txt','r')

except TypeError:

print('no file.')

输出

====================== RESTART: C:/Python34/xuexi/1.py ======================Traceback (most recent call last):  

File "C:/Python34/xuexi/1.py", line 2, in

f=open('a.txt','r')

FileNotFoundError: [Errno 2] No such file or directory: 'a.txt'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):  File "C:/Python34/xuexi/1.py", line 3, inexcept typeerror:

NameError: name 'typeerror' is not defined


TypeError改为FileNotFoundError

try:

f=open('a.txt','r')

except TypeError:

print('no file.')

输出

no file.

>>>


当文件存在时,输出为2.txt的内容


try:

f=open('2.txt','r')

print(f.read())

f.close()

except TypeError:

print('no file.')

输出

ID

age

abc

>>>        


当文件存在时,      

try:

f=open('2.txt','r')

print(f.read())

except IOError:

print('no file.')

except TypeError:

print('type error.')

except:

print("other error.")

else:

print("file exist")

finally:

print("done")

输出

ID

age

abc

file exist

done

>>>


当文件不存在时,

try:

f=open('2q.txt','r')

print(f.read())

except IOError:

print('no file.')

except TypeError:

print('type error.')

except:

print("other error.")

else:

print("file exist")

finally:

print("done")

输出

no file.

done

>>>


import traceback

try:

a=b

b=c

except:

f=open('log.txt','a')       #a附加

f.flush()                        #flush 写入缓存

traceback.print_exc(file=f)

finally:

print("save log.")

f.close()

输出

save log.

>>>



a=None

try:

if a=='None':

raise Exception("not object")    #不管有没有,都定义为异常

print("a is null")

except:

print("error")

finally:

print("Done")

输出

Done

>>>


import time

try:

f=open('1.txt')

while True:

line =f.readlines()      #当有1.txt这个文件时,输出结果

if len(line)==0:        #如果行等于0

break

time.sleep(2)          #等2秒

print(line)

finally:

f.close()

输出

['ID\n', 'age\n', 'aaa']

>>>

相关文章

网友评论

      本文标题:python学习笔记(12月28日)-python异常

      本文链接:https://www.haomeiwen.com/subject/yjtuvttx.html