import pickle # #1、从文件中读取pickle格式 with open('egon.json','rb') as f: pkl=f.read() #2、将json_str转成内存中的数据类型 dic=pickle.loads(pkl) print(dic['a']) #1和2可以合作一步 with open('db.pkl','rb') as f: dic=pickle.load(f) print(dic['a']) # pickle 的序列化 import json,pickle s={1,2,3} # json.dumps(s) pickle.dumps(s) import pickle dic={'a':1,'b':2,'c':3} # 1 序列化 pkl=pickle.dumps(dic) # 字典序列化后变成字节,不是字符串 print(pkl,type(pkl)) # #2 写入文件 with open('db.pkl','wb') as f: # 对应的写入文件就应该是wb模式写入 f.write(pkl) # 1和2可以合作一步 with open('db.pkl','wb') as f: pickle.dump(dic,f)
# json格式不能识别单引号,全都是双引号 import json with open('db1.json','rt',encoding='utf-8') as f: json.load(f) json.loads('{"name":"egon"}') import json print(json.loads("{'name':'egon'}")) #会报错,json文件里不存在单引号。反序列化对象里面不能有单引号 with open('db.json','wt',encoding='utf-8') as f: l=[1,True,None] json.dump(l,f) # 用json反序列化 with open('db.json','rt',encoding='utf-8') as f: l=json.load(f) print(l) # 用eval反序列化:eval只是单纯的将文件里的字符串运行变成对应的数据类型,而不会把json文件里卖弄的true,null转换成True,None with open('db.json','rt',encoding='utf-8') as f: s=f.read() #s ='[1, true, null]' dic=eval(s) #eval('[1, true, null]') print(dic['name'])