-
Notifications
You must be signed in to change notification settings - Fork 0
/
readFile.py
55 lines (51 loc) · 1.14 KB
/
readFile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import os
'''
使用if判断
'''
print("first read ------- ")
data = open("sketch.txt")
for word in data :
if not word.find(":") == -1:
(role,line_word) = word.split(":", 1)
print(role, end = "")
print(" said ", end = "")
print(line_word,end = "")
data.close()
'''
使用try except异常捕捉
'''
print("\nsecond read ------- ")
data = open("sketch.txt")
for word in data :
try:
(role,line_word) = word.split(":", 1)
print(role, end = "")
print(" said ", end = "")
print(line_word,end = "")
except ValueError:
pass
data.close()
print("\nthird read ------- ")
if os.path.exists("zhangtao.txt"):
data = open("zhangtao.txt")
for word in data :
if not word.find(":") == -1:
(role,line_word) = word.split(":", 1)
print(role, end = "")
print(" said ", end = "")
print(line_word,end = "")
data.close()
print("\nfour read ------- ")
try:
data = open("zhangtao.txt")
for word in data :
try:
(role,line_word) = word.split(":", 1)
print(role, end = "")
print(" said ", end = "")
print(line_word,end = "")
except ValueError:
pass
data.close()
except IOError:
print("file is missing !")