Python提供了一个标准库,名为Pickle,它可以保存和加载几乎任何Python数据对象,包括列表。
同时,官方文档也是对剑使用Pickle进行序列化处理,除此之外,Python中还有一个marshal可以用来序列化,不过似乎比较不好用,比如说会对已经序列化的数据重新序列化进而导致无法识别,不支持用户自定义类的序列化,版本不兼容。
截止到Python3.4版本,pickling共有0-4五个版本,版本越高,功能越强,越没法直接阅读。
pickle包括两个主要的方法
pickle.dump(obj, file, protocol=None, *, fix_imports=True) 保存数据
pickle.load(file, *, fix_imports=True, encoding="ASCII", errors="strict") 加载数据
代码:
#pickle test #to save and load data from disk with pickle import pickle #save data def save_data(data,file_name): try: with open(file_name,‘wb‘) as file_out: pickle.dump(data,file_out) except pickle.PickleError as perr: print(‘Pickling error:‘+str(perr)) #load data def load_data(file_name): try: with open(file_name,‘rb‘) as file_in: data=pickle.load(file_in) print(data) except pickle.PickleError as perr: print(‘Pickling error:‘+str(perr))
Head Frist Python 读书笔记 第4章 “腌制”数据
原文:http://www.cnblogs.com/lvjianwei/p/5173616.html