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!

python学习二(文件与异常)的更多相关文章

  1. Python学习二:词典基础详解

    作者:NiceCui 本文谢绝转载,如需转载需征得作者本人同意,谢谢. 本文链接:http://www.cnblogs.com/NiceCui/p/7862377.html 邮箱:moyi@moyib ...

  2. 【python学习笔记】8.异常

    [python学习笔记]8.异常 raise Exception: 抛出指定异常 try/except: 捕捉异常 except: 第一个参数是需要捕获的异常类型,可以是多个类型组成元组,第二个参数是 ...

  3. python学习9—文件基本操作与高级操作

    python学习9—文件基本操作与高级操作 1. 文件基本操作 打开文件,获得文件句柄:f = open('filename',encoding='utf-8'),open会查询操作系统的编码方式,并 ...

  4. python学习笔记十:异常

    一.语法 #!/usr/bin/python filename='hello' #try except finally demo try: open('abc.txt') print hello ex ...

  5. [Python学习笔记]文件的读取写入

    文件与文件路径 路径合成 os.path.join() 在Windows上,路径中以倒斜杠作为文件夹之间的分隔符,Linux或OS X中则是正斜杠.如果想要程序正确运行于所有操作系统上,就必须要处理这 ...

  6. Python学习--13 文件I/O

    Python内置了读写文件的函数,用法和C是兼容的. 读写文件前,我们先必须了解一下,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘,所以,读写文件就是请求操作系 ...

  7. python学习总结---文件操作

    # 文件操作 ### 目录管理(os) - 示例 ```python # 执行系统命令 # 清屏 # os.system('cls') # 调出计算器 # os.system('calc') # 查看 ...

  8. 03 python学习笔记-文件操作(三)

    本文内容主要包括以下方面: 1. 文件操作基本认识2. 只读(r, rb)3. 只写(w, wb)4. 追加(a, ab)5. r+读写6. w+写读7. a+写读(追加写读)8. 文件的修改 一.文 ...

  9. Python学习_06_文件、IO

    文件对象 python中的文件操作和c语言比较类似,包括一些缓冲.偏移量的方式. 文件对象可以通过open().file()两个内建方法创建,两个方法并没有什么不同,使用方法和c语言中的fopen() ...

随机推荐

  1. Oracle中生成UUID

    Oracle中生成跨系统的唯一识别符UUID非常方便,比生成序列还简单,直接用sys_guid()就行, 例如select sys_guid() from dual 会产生一个跟MAC地址.生成时间相 ...

  2. 异常:Project configuration is not up-to-date with pom.xml解决方案

    转自:https://www.cnblogs.com/zhujiabin/p/6343423.html 1. Description    Resource    Path    Location   ...

  3. Structuring Machine Learning Projects 笔记

    1 Machine Learning strategy 1.1 为什么有机器学习调节策略 当你的机器学习系统的性能不佳时,你会想到许多改进的方法.但是选择错误的方向进行改进,会使你花费大量的时间,但是 ...

  4. linux 环境变量恢复默认值

    export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin 在linux命令下如何访问一个ur ...

  5. 1.2 DVWA亲测sql注入漏洞(blind)

    LOW等级     我们尝试输入:   即如果页面返回为假,则说明后面的语句成功注入 据此我们可以知道 1' and 真 --> 页面显示 “User ID exists in the data ...

  6. HTML5学习笔记(六)web worker

    当在 HTML 页面中执行脚本时,页面的状态是不可响应的,直到脚本已完成.web worker 是运行在后台的 JavaScript,不会影响页面的性能,页面可以响应. 在创建 web worker ...

  7. 微信小程序小结(2) ------ 自定义组件

    在小程序中有模板跟组件的概念.但模板更多的用于内容的展示,更复杂的交互逻辑就没办法了.所以在小程序中也定义了一些组件来解决一些简单逻辑的功能. 但有时预定义的组件并不能满足我们的需求,这时就需要我们自 ...

  8. 洛谷P3792 由乃与大母神原型和偶像崇拜

    P3792 由乃与大母神原型和偶像崇拜 题目背景 由乃最近没事干,去研究轻拍学去了 就是一个叫做flip flappers,轻拍翻转小膜女的番 然后研究的过程中她看到了一个叫做大母神原型的东西 大母神 ...

  9. 洛谷P1083 借教室

    P1083 借教室 题目描述 在大学期间,经常需要租借教室.大到院系举办活动,小到学习小组自习讨论,都需要向学校申请借教室.教室的大小功能不同,借教室人的身份不同,借教室的手续也不一样. 面对海量租借 ...

  10. POJ1036 Gangsters

    题目来源:http://poj.org/problem?id=1036 题目大意: 有N个强盗要进入一家饭店打劫,第i个强盗在Ti时刻到达,会抢到Pi的财产.饭店的门有K+1状态,门打开的程度为[0, ...