Python自动化开发从浅入深-语言基础(pickle)
pickle可以将对象以文件的形式保存到磁盘上,称之为对象序列化,pickle.dump(obj, file[, protocol])是对象序列化的格式,它将obj序列化结果数据流写入到file文件对象中。
参数protocol是序列化模式,默认值为0,表示以文本的形式序列化。protocol的值还可以是1或2,表示以二进制的形式序列化,1是老式的二进制协议;2是2.3版本引入的新二进制协议,较以前的更高效。其中协议0和1兼容老版本的python。
pickle.load(file)称为反序列化对象。从磁盘中读取文件,将文件中的数据解析为一个Python对象。
import pickle
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def show(self,stat):
if stat == 1:
print ("Write To File:\nName is %s,Age is %s"%(self.name,str(self.age)))
elif stat == 2:
print ("Raed From File:\nName is %s,Age is %s"%(self.name,str(self.age)))
value1 = Person("zhaohong", 56)
value2 = Person("zhaomeng", 30)
value3 = Person("liuming", 51)
value1.show(1)
value2.show(1)
value3.show(1)
with open('d:/account.txt','wb') as fp:
pickle.dump(value1,fp,0)
pickle.dump(value2,fp,0)
pickle.dump(value3,fp,0)
with open('d:\\account.txt','rb') as fp:
a1 =pickle.load(fp)
a2 =pickle.load(fp)
a3 =pickle.load(fp)
a1.show(2)
a2.show(2)
a3.show(2)
运行结果
Write To File:
Name is zhaohong,Age is 56
Write To File:
Name is zhaomeng,Age is 30
Write To File:
Name is liuming,Age is 51
Raed From File:
Name is zhaohong,Age is 56
Raed From File:
Name is zhaomeng,Age is 30
Raed From File:
Name is liuming,Age is 51
磁盘文件
利用pickle进行序列化时,切记需要clear_memo(),不然python不会进行多次序列化。