您的位置:首页 > 编程语言 > Python开发

Python 文件 和 异常处理

2015-10-14 09:28 603 查看

为什么要用文件

python的列表等数据结构很好用,然而这些代码中的数据都是耦合较高的。

时常需要用到外部数据,也就离不开文件、数据库...

怎么使用文件

关于文件,python的基本输入机制是基于行的。

open() BIF 用来打开文件。

close() BIF 用来关闭文件。

文件常用操作示例

sketch.py

代码段1
#open the data file, and read the first two lines.
data = open('sketch.txt')
print(data.readline(),end = '')
print(data.readline(),end = '')
data.close()


代码段2
data = open('sketch.txt')
data.seek(0)    #return to the head of the file.
for each_line in data:
if not each_line.find(':')==-1:
(role, word) = each_line.split(':',1)
print(role, end = '')
print(' said: ',end = '')
print(word, end ='')
data.close()


代码段3

#<handle exception,suggested method>
try:
data = open('sketch.txt')
for each_line in data:
try:
(role, word) = each_line.split(':',1)
print(role, end = '')
print(' said: ',end = '')
print(word, end ='')
except ValueError:
pass

data.close()
except IOError:
print('The data file is missing!')




代码段1是读入文件并输出前两行的示例。

关于异常处理

后面两段代码,主要用于处理一个不太特殊的“特殊情况”:非标准格式输入造成的程序错误。

解决的方法 要么给出额外的代码逻辑去处理,要么通过异常处理方法解决。

前者的思路很清晰,每次做一件事前先判断是否存在问题,但问题在于:

当需要解决的错误多了,代码很臃肿,代码本来的功能不突出。而且需要人工考虑各种各样的错误,这本身往往并不可行。

后者允许错误发生,在错误发生时捕捉并进行处理。

两种处理方法见代码段2、3。

备注:
1.find(str)方法可以查找str在目标字符串中出现的位置下标, 如果没有出现过该str,则返回-1.

2.split(mark)用于分割字符串,和java的String.split()方法效果类似。

3.try/except类似与java的try/catch 代码段3针对文件不存在,文件行分割错误进行了异常处理。

进一步改进

以上代码需要进一步改进

1.如果发生了异常 关闭文件语句不会被执行,这可能造成一系列严重问题->finally语句

2.还可以让try/except更简洁一点 ->with语句,自带except功能 

(稍后总结)

附: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!


本文参考Head First Python 第三章。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: