finally异常处理
  # finally异常处理
# 代码
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
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 运行结果
12165456478Press ctrl+c now
(Cleaning up: Closed the file)
 1
2
2
1
2
2
编辑  (opens new window)
  上次更新: 2022/12/31, 16:52:27
- 01
 - SpringCache基本配置类05-16
 
- 03
 - Rpamis-security-原理解析12-13
 
 