finally异常处理

finally异常处理

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import sys
import time

f = None
try:
f = open("poem.txt")
# 我们常用的文件阅读风格
while True:
line = f.readline()
if len(line) == 0:
break
print(line, end='')
sys.stdout.flush()
print("Press ctrl+c now")
# 为了确保它能运行一段时间
time.sleep(2) # time.sleep 函数任意在每打印一行后插入两秒休眠
except IOError:
print("Could not find file poem.txt")
except KeyboardInterrupt:
print("!! You cancelled the reading from the file.")
finally: # 始终执行
if f:
f.close()
print("(Cleaning up: Closed the file)")

运行结果

1
2
12165456478Press ctrl+c now
(Cleaning up: Closed the file)
打赏了解一下?
0%