try:
data=open('info.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:
print(each_line)
data.close()
except IOError:
print("File is missing")
Run Code Online (Sandbox Code Playgroud)
当逐行打印文件时,代码往往会在前面添加三个不必要的字符,即"".
实际产量:
Man said: Is this the right room for an argument?
Other Man said: I've told you once.
Man said: No you haven't!
Other Man said: Yes I have.
Run Code Online (Sandbox Code Playgroud)
预期产量:
Man said: Is this the right room for an argument?
Other Man said: I've told you once.
Man said: No you haven't!
Other Man said: Yes I …Run Code Online (Sandbox Code Playgroud)