xinhao 2019-11-08
#对象的存储分为两步:
#1.将对象在内存中的数据抓取取来,转换成一个有序的文本,这一步就是序列化
#2.再将文本存储到磁盘中
import pickle class Bird(object): have_feather = True reproduction_method = "egg"
#创建一个对象
summer = Bird()
pickle_string = pickle.dumps(summer) #已被序列化成二进制数据
with open("summer.pkl", "wb") as fp:
fp.write(pickle_string)
#dump方法可以把上面两步作为一步来完成:
#with open("summer.pkl", "wb") as fp:
#pickle.dump(summer, fp)
#从磁盘文件上恢复对象:先读取文件,再loads
with open("summer.pkl", "rb") as fp: summer = fp.read() #先读取 summer = pickle.loads(summer) #再序列化 print(summer.have_feather)
#或者用load方法,一步到位
#with open("summer.pkl", "rb") as fp:
#summer = pickle.load(fp)
#print(summer.have_feather)