forked from foxli180/HeadFirstPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path05-fileoperator.py
More file actions
72 lines (57 loc) · 2 KB
/
05-fileoperator.py
File metadata and controls
72 lines (57 loc) · 2 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import os
if os.path.exists('sketch1.txt'): #使用if 来对文件是否存在进行逻辑判断
data = open ('sketch1.txt')
for each_line in data:
if each_line.find(':')>0:
(role,line_spoken) = each_line.split(':',1)
print(role ,end ='')
print(' said: ',end ='')
print(line_spoken,end='')
else:
print (each_line,end='')
data.close()
else:
print('Data file is missing!')
print('\n------------------------------------')#使用try来尝试文件是否存在
try:
data = open ('sketch.txt')
for each_line in data:
try:
(role,line_spoken) = each_line.split(':',1)
print(role ,end ='')
print(' said: ',end ='')
print(line_spoken,end='')
except ValueError:
pass
data.close()
except IOError:
print ('Data file is missing!')
print('\n------------------------------------')
print (os.getcwd())
data = open('sketch.txt')
print (data.readline(), end='')
data.seek(0) #Go back to the 1st line
for each_line in data:
print(each_line, end='')
print('\n------------------------------------')
data.seek(0) #Go back to the 1st line
for each_line in data:
if each_line.find(':') > 0:
(role, line_spoken) = each_line.split(':',1)
print (role ,end='')
print (' said: ', end='')
print (line_spoken, end='')
else:
print (each_line, end='')
print('\n------------------------------------')
data.seek(0)
for each_line in data:
try: # try to split each_line, if get exception print the whole line
(role, line_spoken) = each_line.split (':',1)
print (role ,end='')
print (' said: ', end='')
print (line_spoken, end='')
except:
#pass # pass: you can pass the exception
print (each_line, end='')
data.close()