文件基本操作

Python从文本读取数据时,一次会到达一个数据行。

sketch.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?
Other Man: Just now.
Man: No you didn't!
Other Man: Yes I did!
Man: You didn't!
Other Man: I'm telling you, I did!
Man: You did not!
Other Man: Oh I'm sorry, is this a five minute argument, or the full half hour?
Man: Ah! (taking out his wallet and paying) Just the five minutes.
Other Man: Just the five minutes. Thank you.
Other Man: Anyway, I did.
Man: You most certainly did not!
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 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!
(pause)
Man: It's just contradiction!
Other Man: No it isn't!
Man: It IS!
Other Man: It is NOT!
Man: You just contradicted me!
Other Man: No I didn't!
Man: You DID!
Other Man: No no no!
Man: You did just then!
Other Man: Nonsense!
Man: (exasperated) Oh, this is futile!!
(pause)
Other Man: No it isn't!
Man: Yes it is!

需求:读取文件,将上面的对话都加上said

代码如下:

# coding:utf-8
import os # 查看当前工作目录
print(os.getcwd())
# 切换为包含数据文件的文件夹
os.chdir('../../HeadFirstPython/chapter03_except')
# 再次查看当前工作目录
print(os.getcwd()) # 打开文本
data = open('sketch.txt')
# 获取一个数据行,打印
print(data.readline(), end='')
# 再次获取一个数据行,打印
print(data.readline(), end='') # 回到文件原始位置
data.seek(0)
# data.tell() # 等价
for each_line in data:
# 当每一行都存在冒号时,执行if中的操作
if not each_line.find(':') == -1:
# 遇到冒号就切割字符串,返回一个字符串列表,赋至一个目变量元组,则称为多重赋值
# 由于一行字符串中可能有多个: 所以我们需要在使用split方法maxsplit参数
(role, line_spoken) = each_line.split(":", 1)
print(role, end='')
print(' said:', end='')
print(line_spoken, end='') # 关闭文件
data.close()

但是这段代码过于脆弱,但文件格式发生变化或者其他异常情况,还是出问题,这时需要用到异常机制。

处理异常

try/except机制

# coding:utf-8

# 如果文件不存在,异常处理
try:
data = open('sketch.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:
# 如果出现异常,pass,继续执行代码
pass
data.close()
# 想要捕捉特性的异常,需要制定错误类型
except IOError:
print("the data file is missing!")
# 其他所有的异常
except:
print("the data file is broken!")

  

其他:

判断文件是否存在:

os.path.exists('sketch.txt')

Head First Python之3文件与异常的更多相关文章

  1. python学习二(文件与异常)

    Python中使用open BIF与文件交互,与for语句结合使用,一次读取一行 读取文件sketch.txt,文件内容如下: Man: Ah! (taking out his wallet and ...

  2. python进阶(7)--文件与异常

    一.文件读取二.文件写入三.异常四.存储数据 ---------------------------------------分割线:正文-------------------------------- ...

  3. Python的文件及异常

    1. Python的文件及异常 1.1 文件操作 1.1.1 从文件中读取数据 许多情况下,我们的信息是存储在文本中的.例如对用户行为的分析,用户访问系统或者网站的访问信息会被存储于文本中,然后对文本 ...

  4. python入门学习:9.文件和异常

    python入门学习:9.文件和异常 关键点:文件.异常 9.1 从文件中读取数据9.2 写入文件9.3 异常9.4 存储数据 9.1 从文件中读取数据 9.1.1 读取整个文件  首先创建一个pi_ ...

  5. [Python 从入门到放弃] 6. 文件与异常(二)

    本章所用test.txt文件可以在( [Python 从入门到放弃] 6. 文件与异常(一))找到并自行创建 现在有个需求,对test.txt中的文本内容进行修改: (1)将期间的‘:’改为‘ sai ...

  6. Python模块、包、异常、文件(案例)

    Python模块.包.异常.文件(案例) python.py #模块 # Python中的模块(Module),是一个Python文件,以.py文件结尾,包含了Python对象定义和Python语句, ...

  7. Python获得文件时间戳 异常访问监控 邮件定时提醒

    Python获得文件时间戳  异常访问监控 邮件定时提醒

  8. Python之文件和异常IO

    文件和异常 读写文本文件 读取文本文件时,需要在使用open函数时指定好带路径的文件名(可以使用相对路径或绝对路径)并将文件模式设置为'r'(如果不指定,默认值也是'r'),然后通过encoding参 ...

  9. 【Python编程:从入门到实践】chapter10 文件和异常

    chapter10 文件和异常 10.1 从文件中读取数据 10.1.1 读取整个文件 with open("pi.txt") as file_object: contents = ...

随机推荐

  1. Web端优秀图表控件

    百度echart http://echarts.coding.io/doc/example.html C#+JQuery+.Ashx+百度Echarts 实现全国省市地图和饼状图动态数据图形报表的统计 ...

  2. OD 实验(十五) - 对一个程序的逆向

    程序: 打开程序 出现一个 NAG 窗口 这是主界面 点击 Exit 程序出现 NAG 窗口,然后退出 用 PEiD 看一下 是用 VC++ 6.0 写的程序 逆向: 用 OD 载入程序 跑一下程序 ...

  3. nova volume-create的使用

    处理cinder可以直接创建volume外,nova也是可以的 如: 可以看出创建一个名字为volume2的卷,大小为10G 把创建好的volume2卷直接挂在vm虚拟机上 如:先查看计算节点有几个v ...

  4. .net Reactor之限指定设备使用

    .net Reactor之license限指定设备使用 上一篇(https://www.cnblogs.com/s313139232/p/9908400.html)中记录了.net Reactor对d ...

  5. Halcon学习之七:改变图像的现实方式和大小

    change_format ( Image : ImagePart : Width, Height : ) 改变Image图像大小,而且ImagePart图像为灰度值图像. crop_domain ( ...

  6. delphi IOS 后台状态保存

    FormSaveState procedure TFrm.FormSaveState(Sender: TObject);begin end; http://stackoverflow.com/ques ...

  7. Struts2 配置Action详解

     Struts2的核心功能是action,对于开发人员来说,使用Struts2主要就是编写action,action类通常都要实现com.opensymphony.xwork2.Action接口,并实 ...

  8. 大神的---解决tomcat内存溢出问题----tomcat报错:This is very likely to create a memory leak问题解决

    tomcat memory leak解决方案 这种问题在开发中经常会碰到的,看看前辈的总结经验 Tomcat内存溢出的原因  在生产环境中tomcat内存设置不好很容易出现内存溢出.造成内存溢出是不一 ...

  9. jira 安装

    jira jira是Atlassian公司出品的项目与事务跟踪工具,被广泛应用于缺陷跟踪(bug管理).客户服务.需求收集.流程审批.任务跟踪.项目跟踪和敏捷管理等工作领域.同禅道等类似. 安装前准备 ...

  10. keepalived和zookeeper对比

    https://blog.csdn.net/vtopqx/article/details/79066703keepalived与zookeeper都可以用来实现高可用,高可用一般跟负载均衡会一起考虑, ...