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

python系列学习二——文件操作及异常处理

2013-12-03 16:07 1136 查看

1. 文件操作

1)open(filename) 打开一个文件句柄

2)file_handle.close() 关闭已打开的文件

3)file_handle.readline() 从文件获取一个数据行

4)file_handle.seek(0) 返回到文件的起始位置



2. 数据处理

split(sep, max) 分割字符串,max为最大分割次数



可以看到,上述执行的结果产生了一个ValueError,查看文档内容,可以发现出现错误的那行数据没有冒号导致,由于缺少冒号,split()无法完成它的工作,因此导致运行错误。

3. 异常处理

有异常发生,就需要进行异常处理,那么该如何处理异常呢?

1)增加额外的逻辑来进行相关处理,如果有更多的问题,就需要更多的代码

2)允许错误发生,在各个错误发生时分别处理相应错误

3.1 增加额外逻辑
var_str.find(sub_str) 找出字符串中的字串,返回字串在原字符串中的索引位置. 如果无法找到,返回-1

可以通过find()方法判断当前行的内容是否有冒号,满足条件的数据才进行相关处理:

var_file = open('sketch.txt')
for line in var_file:
if not line.find(':') == -1:
(role, words) = line.split(':', 1)
print role,
print ' said: ',
print words,
var_file.close()


上述代码执行结果:



可以看到,ValueError没有了。

3.2 异常处理程序(try...except...)
try/except机制,这个语句就是提供一个途径,可以在运行时系统地处理异常和错误。格式如下:

try:

    代码逻辑(可能导致一个运行错误)

catch:

    错误恢复代码

使用pass语句来忽略错误的发生:

var_file = open('sketch.txt')
for line in var_file:
try:
(role, words) = line.split(':', 1)
print role,
print ' said: ',
print words,
except:
pass
var_file.close()


上述程序运行结果与3.1的结果是一致的。

3.3 特定指定异常
假如要打开的文件被删除或者改名,即缺少数据文件时,上面两个程序都会产生一个IOError.

方法一:增加额外的错误检查代码

import os
if os.path.exists('sketch.txt'):
data = open('sketch.txt')
for item in data:
if not item.find(':') == -1:
(role, words) = item.split(':', 1)
print role,
print ' said: ',
print words,
data.close()
else:
print 'The data file is missing!'


方法二:使用异常处理
try:
var_file = open('sketch.txt') for line in var_file: try: (role, words) = line.split(':', 1) print role, print ' said: ', print words, except: pass var_file.close()
except:
print 'The data file is missing!'


上述两种方案运行结果都正常。但随着你必须考虑的异常越来越多,增加额外代码和逻辑的复杂性也随之增加,最后可能会掩盖程序的本来作用;而异常处理方式就不存在这个问题,可以一目了然的看出程序的主要作用。谨慎使用try语句可以让代码更易读、易写,出问题时更容易修正。此外异常处理可以指定错误类型,将一般化的异常处理转化为特定的异常处理:
try:
var_file = open('sketch.txt')
for line in var_file:
try:
(role, words) = line.split(':', 1)
print role,
print ' said: ',
print words,
except ValueError:
pass
var_file.close()
except IOError:
print 'The data file is missing!'

4. 数据存储

使用open()打开磁盘文件时,可以指定访问模式。默认地,open()使用模式r表示读,要打开一个文件完成写,需要使用模式r,如:

out = open('data.out', 'w'),

使用访问模式w时,Python会打开指定的文件来完成写,如果这个文件已存在,则会清空它现有的内容;

要追加到一个文件,需要使用访问模式a;

要打开一个文件来完成写和读(不清除),需要使用w+;

如果想打开一个文件完成写,但是这个文件并不存在,那么首先会为你创建这个文件,然后在打开文件进行写。

将sketch.txt文件中两个人的讲话分别保存到两个磁盘文件中:

#!/usr/local/bin/python
# coding=utf-8
# 使用cPickle/pickle可以在文件中存储任何对象(dump/load)
import cPickle as p
man = []
other = []
try:
v_file = open('sketch.txt')
for line in v_file:
try:
(role, words) = line.split(':', 1)
words = words.strip();
if role == 'Man':
man.append(words)
elif role == 'Other Man':
other.append(words)
except ValueError:
pass
v_file.close()
except IOError:
print 'The data file is missing!'

try:
man_file = open('man_data.txt', 'w')
other_file = open('other_data.txt', 'w')
p.dump(man, man_file)
p.dump(other, other_file)
except IOError:
print 'file error!'
except p.PickleError as perr: # 如果dump数据除了问题,会产生一个PickleError
print 'cPickle error: ' + str(perr)
# 用finally扩展try,不论是否出现异常,都会执行finally组代码
finally:
man_file.close()
other_file.close()


5. 异常信息显示

#!/usr/local/bin/python
# coding=utf-8
try:
v_file = open('missing.txt')
print v_file.readline()
except IOError as err:  #为异常对象指定一个名
print 'File error: ' + str(err)  #使用str()将对象转换为字符串
finally:
# 检查v_file是否已定义,locals()返回当前作用域中定义的所有名的集合,in操作符测试成员关系
if 'v_file' in locals():
v_file.close()
上述代码执行结果:

File error: [Errno 2] No such file or directory: 'missing.txt'

6. 用with处理文件

使用with时,不需要操心关闭打开的文件,python解释器会自动为你考虑这一点。

#!/usr/local/bin/python
# coding=utf-8
try:
with open('test.txt', 'w') as v_file:
v_file.write("It's a test file.")
except IOError as err:  #为异常对象指定一个名
print 'File error: ' + str(err)  #使用str()将对象转换为字符串
with语句利用了一种名为上下文管理协议(context management protocol)的python技术。
#!/usr/local/bin/python
# coding=utf-8
import cPickle as p
try:
with open('man_data.txt') as man_file, open('other_data.txt') as other_file:
man = p.load(man_file)
other = p.load(other_file)
print man
print other
except IOError as err:
print 'File error: ' + str(err)
except p.PickleError as peer:
print 'cPickle error: ' + str(peer)


小结

1. 使用open()打开一个磁盘文件,创建一个迭代器从文件读取数据,一次读取一个数据行

2. readline()方法从一个打开的文件读取一行数据

3. seek()方法将文件退回到起始位置

4. close()方法关闭一个之前打开的文件

5. split()方法将一个字符串分解为一个字串列表

6. Python中不可改变的常量列表成为元组(tuple). 一旦将列表数据赋至一个元祖,就不能再改变. 元组是不可改变的

7. 数据不符合期望的格式时会出现ValueError

8. 数据无法正常访问时会出现IOError

9. help()可以在shell中访问python的文档

10. find()方法在一个字符串中查找一个指定字串

11. not 关键字将一个条件取反

12. try...except...语句提供了一个异常处理机制,保护运行时可能出错的代码

13. pass语句是python的空语句或null语句,什么也不做

14. strip()方法去掉字符串手尾的空白字符

15. print()的file参数控制将数据发送/保存到哪里(v 3.x)

16. finally组总会执行,不论try/except语句中出现什么异常

17. except 组会传入一个异常对象,使用as关键字可赋至一个标识符

18. str()用来将其他数据类型对象转换为字符串表示

19. locals()返回当前作用域中的变量集合

20. in 操作符用于检查成员关系

21. ‘+’ 操作符用于字符串时,联接两个字符串;用于数字时,将两个数相加

22. with语句会自动处理所有已打开文件的关闭工作,即使出现异常也不例外,with语句也使用as关键字

23. sys.stdout是python中所谓的标准输出,可以从标准库的sys模块访问

24. 标准库pickle/cPickle模块可以高效地将python数据对象保存到磁盘文件以及从磁盘文件中恢复, dump()用于保存,load()用于恢复



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python