Head First Python之3文件与异常
文件基本操作
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文件与异常的更多相关文章
- python学习二(文件与异常)
Python中使用open BIF与文件交互,与for语句结合使用,一次读取一行 读取文件sketch.txt,文件内容如下: Man: Ah! (taking out his wallet and ...
- python进阶(7)--文件与异常
一.文件读取二.文件写入三.异常四.存储数据 ---------------------------------------分割线:正文-------------------------------- ...
- Python的文件及异常
1. Python的文件及异常 1.1 文件操作 1.1.1 从文件中读取数据 许多情况下,我们的信息是存储在文本中的.例如对用户行为的分析,用户访问系统或者网站的访问信息会被存储于文本中,然后对文本 ...
- python入门学习:9.文件和异常
python入门学习:9.文件和异常 关键点:文件.异常 9.1 从文件中读取数据9.2 写入文件9.3 异常9.4 存储数据 9.1 从文件中读取数据 9.1.1 读取整个文件 首先创建一个pi_ ...
- [Python 从入门到放弃] 6. 文件与异常(二)
本章所用test.txt文件可以在( [Python 从入门到放弃] 6. 文件与异常(一))找到并自行创建 现在有个需求,对test.txt中的文本内容进行修改: (1)将期间的‘:’改为‘ sai ...
- Python模块、包、异常、文件(案例)
Python模块.包.异常.文件(案例) python.py #模块 # Python中的模块(Module),是一个Python文件,以.py文件结尾,包含了Python对象定义和Python语句, ...
- Python获得文件时间戳 异常访问监控 邮件定时提醒
Python获得文件时间戳 异常访问监控 邮件定时提醒
- Python之文件和异常IO
文件和异常 读写文本文件 读取文本文件时,需要在使用open函数时指定好带路径的文件名(可以使用相对路径或绝对路径)并将文件模式设置为'r'(如果不指定,默认值也是'r'),然后通过encoding参 ...
- 【Python编程:从入门到实践】chapter10 文件和异常
chapter10 文件和异常 10.1 从文件中读取数据 10.1.1 读取整个文件 with open("pi.txt") as file_object: contents = ...
随机推荐
- servlet对应.net中的http上下文
java中的servlet在.net中其实就是http上下文.
- Linux 服务器--Iptables 端口转发
日常Iptables 端口转发 需求:公司是局域网络,通过一个外网ip,进行互联网的访问.公司的云平台服务器在公网中,虚拟化平台中有一台内部服务器,用于公司某部门的使用,上面运行www 服务,ssh端 ...
- chaep
Talk is cheap,show me the code! { job;/sbin/halt -p; } 关于shell脚本中提醒用法及参数输入 if [[ $# -ne 1 ]] then ec ...
- [转] 从数据库中读取图片并导入Excel文件,C#方式
原文地址, 作者 Lvyou1980 直接源码吧. using System; using System.IO; using System.Data; using System.Drawing; us ...
- 学习 Python 编程的 19 个资源 (转)
学习 Python 编程的 19 个资源 2018-01-07 数据与算法之美 编译:wzhvictor,英文:codecondo segmentfault.com/a/119000000418731 ...
- Spring 中的 LocalSessionFactoryBean和LocalContainerEntityManagerFactoryBean
Spring和Hibernate整合的时候我们经常会有如下的配置代码 1,非JPA支持的配置 <!-- 配置 Hibernate 的 SessionFactory 实例: 通过 Spring 提 ...
- html 中的media属性
在css中我们使用media标签来区分调用哪个css样式,比如使用media="print"来表示当执行打印文档时,使用print.css样式.这样使得文档更有得于打印,如将页面宽 ...
- Mysql 源码编译安装 ( 5.5 、5.6 共存 )
简介: 如何在一台服务器同时运行两 ( 多 ) 个 MySQL 服务. 1.MySQL 5.6 shell > useradd -r -s /sbin/nologin mysql shell & ...
- properties 中文乱码问题的解决
在用properties处理配置信息时,发现有时出现中文乱码的问题,后经查资料得知是由于编码不一致引起的.于是解决之. [原理解释] 我们用 API操作properties文件,如果获取的属性值是中文 ...
- maven创建webapp项目
新建maven项目 勾选 create a simple project 点击next 填写maven项目信息,packaging 选择war,点击Finish 创建成功后,项目结构如下 选择项目右键 ...