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

本文深入探讨了如何通过Python脚本读取并解析数据文件,具体展示了使用sketch.py读取并打印datafile.txt中角色及其对话的流程。文章详细说明了错误处理机制及脚本执行过程。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值