[Head First Python]3. 文件与异常:处理错误

datafile.txt

Man: Is this the right room for an argument?
Other Man: I've told you once.
Man: No you haven't
Other Man:Yes I have
Man: When? and :
(pause)
Other Man: Just now.
Man: No you didn't!

sketch.py

 1 try:
 2     data = open ("datafile.txt")
 3 
 4     for each_line in data:
 5         try:
 6             (role, line_spoken) = each_line.split(":", 1)
 7             print(role, end = '')
 8             print(" said :", end = '')
 9             print(line_spoken, end = '')
10         except ValueError:
11             pass
12 
13     data.close()
14 except IOError:
15     print('this data file is missing!')

 if语句取反用 not

if not each_line.find(':') == -1

原文地址:https://www.cnblogs.com/galoishelley/p/3792988.html