Pickle
pickle中最主要的两个函数对为dump()和load(),分别用来进行对象的序列化和反序列化。
pickle.dump(obj, file[, protocol])
:序列化数据到一个文件描述符(一个打开的文件、套接字等)
load(file)
: 反序列化
import cPickle as pickle
mydata={}
fp=open{"picklefile","wb"}
pickle.dump(mydata,fp)
fp.close()
fp=open{"picklefile.dat","rb"}
out
- 通用性(linux-windows)
- 数据类型广泛(可序列化的元组、字典、列表、非嵌套函数、类)
- 可拓展
- 维护对象引用关系
自用的pickle函数
import pickle, pprint
def pickle_save():#使用pickle模块将数据对象保存到文件
contact = {'julius1':{'cellphone':'13800000000','tel':'0512-34343534','qq':'354564656'},
'julius2':{'cellphone':'13300000000','tel':'0513-34343534','qq':'454564656'},
'julius3':{'cellphone':'13400000000','tel':'0514-34343534','qq':'554564656'},
'julius4':{'cellphone':'13500000000','tel':'0515-34343534','qq':'654564656'}
}
f = open('contact_list.txt','w')
pickle.dump(contact,f)
f.close()
def pickle_load():#使用pickle从文件中重构python对象
f = open('contact_list.txt','r')
contact = pickle.load(f)
pprint.pprint(contact)
pprint.pprint(contact['julius2'])#从dict中按要求取值
pprint.pprint(contact['julius3']['cellphone'])
pprint.pprint(contact['julius4']['qq'])
f.close()
pickle_save()
pickle_load()
https://blog.csdn.net/julius_lee/article/details/14163207
可能的错误:
ERROR:write() argument must be str, not bytes
SOLUTION:文件打开用二进制
f=open("list_account.pkl","w")改为
f=open("list_account.pkl","wb+")
Json
Json是文本的,输出unicode,pickle是二进制的。
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
# 序列化obj到fp
json.load(fp/s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
# 反序列化为obj
json.dumps([1, 2, 3, {'4': 5, '6': 7}],separators=(',', ':'))
>>>'[1,2,3,{"4":5,"6":7}]'
注意:
- fp必须支持.write 和str输入