HeadFirstPython-数据持久化

#!/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(sketch_file)
"对文件内容进行迭代"
for each_item in data:
try:
"把each_item里每一行内容进行分割,并赋值到role,line_spoken上,最大分割一次"
(role,line_spoken) = each_item.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:
"这个文件程序会自动帮我们创建,如果文件已经存在的话那么它会覆盖文件"
man_data_file = open("/Users/chenbaocheng/Desktop/HeadFirstPython/chapter3/man_data.txt",'w')
other_data_file = open("/Users/chenbaocheng/Desktop/HeadFirstPython/chapter3/other_data.txt",'w')

print >> man_data_file,man
print >> other_data_file,other

except IOError:
print('the file is minning')

finally:
man_data_file.close()
other_data_file.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/man_data1.txt",'w') as man_data1, open("/Users/chenbaocheng/Desktop/HeadFirstPython/chapter3/other_data1.txt",'w') as other_data1:
print >> man_data1,man
print >> other_data1,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/man_data100",'wb') as man_data1, open("/Users/chenbaocheng/Desktop/HeadFirstPython/chapter3/other_data100",'wb') as other_data1:
"将数据存入到二进制的文件里"
pickle.dump(man,man_data1)
pickle.dump(other,other_data1)

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/man_data100",'rb') as read_man_data1:
print "正在取数据" , "." *8
print pickle.load(read_man_data1)
except IOError as e:
print 'File Error: ' + str(e)
except pickle.PickleError as perr:
print 'PickleError: ' + str(perr)

posted @ 2014-02-20 22:47  1万小时理论  阅读(427)  评论(0编辑  收藏  举报