Python-100-Days/Day01-15/code/Day11/ex3.py

29 lines
602 B
Python
Raw Normal View History

2018-04-27 00:00:22 +08:00
"""
异常机制 - 处理程序在运行时可能发生的状态
Version: 0.1
Author: 骆昊
Date: 2018-03-13
"""
import time
import sys
filename = input('请输入文件名: ')
try:
2019-05-03 21:17:36 +08:00
with open(filename) as f:
lines = f.readlines()
2018-04-27 00:00:22 +08:00
except FileNotFoundError as msg:
2019-05-03 21:17:36 +08:00
print('无法打开文件:', filename)
print(msg)
2018-04-27 00:00:22 +08:00
except UnicodeDecodeError as msg:
2019-05-03 21:17:36 +08:00
print('非文本文件无法解码')
sys.exit()
2018-04-27 00:00:22 +08:00
else:
2019-05-03 21:17:36 +08:00
for line in lines:
print(line.rstrip())
time.sleep(0.5)
2018-04-27 00:00:22 +08:00
finally:
2019-05-03 21:17:36 +08:00
# 此处最适合做善后工作
print('不管发生什么我都会执行')