Python中使用open BIF与文件交互,与for语句结合使用,一次读取一行

读取文件sketch.txt,文件内容如下:

Man: Ah! (taking out his wallet and paying) Just the five minutes.
Other Man: Just the five minutes. Thank you.
Other Man: Now let's get one thing quite clear: I most definitely told you!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh look, this isn't an argument!
(pause)
Other Man: Yes it is!
Man: No it isn't!

上文中说话人与所说的内容用:隔开。要求程序处理,在说话人的后面加上said,例如

Man said What's your name?

Other Man said My name is Bruce。

注意上文中的第3、7行,第3行中有两个:号,第7行没有:号

代码1

data = open('sketch.txt')

for each_line in data:
(role, line_spoken) = each_line.split(':', 1)
print(role, end='')
print(' said: ', end='')
print(line_spoken, end='') data.close()

split(':',1)表示数据只会根据遇到的第1个':'号分成两个部分,这样就消除了上文中第3行额外':'号的影响。

打印结果如下:红色部分为打印的ValueError异常,因为第7行没有':'号

Man said: Ah! (taking out his wallet and paying) Just the five minutes.
Other Man said: Just the five minutes. Thank you.
Other Man said: Now let's get one thing quite clear: I most definitely told you!
Man said: Oh no you didn't!
Other Man said: Oh yes I did!
Man said: Oh look, this isn't an argument!
Traceback (most recent call last):
File "E:\workspace\PythonTest\chapter3\page81.py", line 4, in <module>
(role, line_spoken) = each_line.split(':', 1)
ValueError: need more than 1 value to unpack

改写代码,处理异常

try:
data = open('sketch.txt') for each_line in data:
try:
(role, line_spoken) = each_line.split(':')
print(role, end='')
print(' said ', end='')
print(line_spoken, end='')
except ValueError:
pass data.close()
except IOError:
print('The datafile is missing!')

pass表示捕获异常后不做任务处理,正确打印结果如下

Man said Ah! (taking out his wallet and paying) Just the five minutes.
Other Man said Just the five minutes. Thank you.
Man said Oh no you didn't!
Other Man said Oh yes I did!
Man said Oh look, this isn't an argument!
Other Man said Yes it is!
Man said No it isn't!

最新文章

  1. centos分区
  2. fastcgi安装
  3. Aspect Oriented Programming (AOP)
  4. 无法作为数据库主体执行,因为主体 &quot;dbo&quot; 不存在、无法模拟这种类型的主体,或您没有所需的权限。 已将数据库上下文更改为
  5. [direct-X] direct-X最小框架
  6. LeetCode——Gas Station
  7. Notepad++ 配置java编译环境
  8. Fitnesse启动参数与配置
  9. Unity问答——请教一下NGUI的图片转换问题
  10. @RestController
  11. C++ 虚函数相关,从头到尾捋一遍
  12. 如何实现一个malloc(转)
  13. 不懂这些高并发分布式架构、分布式系统的数据一致性解决方案,你如何能找到高新互联网工作呢?强势解析eBay BASE模式、去哪儿及蘑菇街分布式架构
  14. AttributeError: Got AttributeError when attempting to get a value for field `password2` on serializer ` UserSerializer`...
  15. orz gzy
  16. (13)How to stay calm when you know you&#39;ll be stressed
  17. Informix 常用函数
  18. Altium Designer 基本封装
  19. ErrorProvider控件使用
  20. MeasureSpec介绍及使用详解

热门文章

  1. Amaze UI 框架
  2. Java 的 Tuple 元组数据类型
  3. SEO优化-伪静态-URLRewrite 详解
  4. @JsonProperty 注解
  5. Django框架之第三篇模板语法
  6. Servlet编程实例
  7. mongodb创建.bat快捷方式
  8. sklearn实现聚类
  9. Prim算法:最小生成树---贪心算法的实现
  10. grep的常用命令语法