!/usr/bin/env python
coding=utf-8
"""这一章主要是讲如何将数据进行持久化。使用pickle对数据进行腌制。
在对数据进行腌制之前,我们需要对数据进行格式化;
针对数据来源,取出我们想要的数据。在中间的知识点是 文件打开与关闭,以及其异常处理。 我用的是Python2.7 在某些语法上与HeadFirstPython原书有些不一样。
"""import pickle import os
sketch_file = "/Users/chenbaocheng/Desktop/HeadFirstPython/chapter3/sketch.txt"
"新建立两个列表"man = [] other = []
"使用try/except对当前代码出错进行异常定义"try: data = open(sketchfile) "对文件内容进行迭代" for eachitem in data: try: "把eachitem里每一行内容进行分割,并赋值到role,linespoken上,最大分割一次" (role,linespoken) = eachitem.split(‘:‘,1)
"将line_spoken里多作的空格去除"
line_spoken = line_spoken.strip()
"对role进行判断,不同的人说的话加入到"
if role == ‘Man‘:
man.append(line_spoken)
elif role == ‘Other Man‘:
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError: print "the file is missing"
try: "这个文件程序会自动帮我们创建,如果文件已经存在的话那么它会覆盖文件" mandatafile = open("/Users/chenbaocheng/Desktop/HeadFirstPython/chapter3/mandata.txt",‘w‘) otherdatafile = open("/Users/chenbaocheng/Desktop/HeadFirstPython/chapter3/otherdata.txt",‘w‘)
print >> man_data_file,man
print >> other_data_file,other
except IOError: print(‘the file is minning‘)
finally: mandatafile.close() otherdatafile.close()
"下面是一段有意思的代码"try: "ccc.txt这个文件是不存在的,一旦运行,就会立即报错,这个报错在未添加locals那行代码之前,文件是不会被关闭的。" data = open("ccc.txt") print data.read() except IOError as e: print ‘File error: ‘ + str(e) finally: "下面这个locals是在python命名空间中去找data,因为在第一步打开了,所以在这一步如果它在locals里,那么现要将其关闭" if ‘data‘ in locals(): data.close()
"使用open ...with可以不用关于心文件是否关闭了"
"再经过一次改版的,可以将多个open放到一行里"try: with open("/Users/chenbaocheng/Desktop/HeadFirstPython/chapter3/mandata1.txt",‘w‘) as mandata1, open("/Users/chenbaocheng/Desktop/HeadFirstPython/chapter3/otherdata1.txt",‘w‘) as otherdata1: print >> mandata1,man print >> otherdata1,other
except IOError as e: print ‘File Error: ‘ + str(e)
"现在我们看下之前生的文件是否可以被读取"with open("/Users/chenbaocheng/Desktop/HeadFirstPython/chapter3/other_data.txt") as test: print test.read()
"下一部分讲 使用pickle来将数据进行持久化"try: with open("/Users/chenbaocheng/Desktop/HeadFirstPython/chapter3/mandata100",‘wb‘) as mandata1, open("/Users/chenbaocheng/Desktop/HeadFirstPython/chapter3/otherdata100",‘wb‘) as otherdata1: "将数据存入到二进制的文件里" pickle.dump(man,mandata1) pickle.dump(other,otherdata1)
except IOError as e: print ‘File Error: ‘ + str(e)
except pickle.PickleError as perr: print ‘PickleError: ‘ + str(perr)
"读取pickle里的数据"try: with open("/Users/chenbaocheng/Desktop/HeadFirstPython/chapter3/mandata100",‘rb‘) as readmandata1: print "正在取数据" , "." *8 print pickle.load(readman_data1) except IOError as e: print ‘File Error: ‘ + str(e) except pickle.PickleError as perr: print ‘PickleError: ‘ + str(perr)