IO编程----序列化
pickle
import pickle d={'name':'Bob','age':20,'score':88} ''' pickle.dump直接将对象序列化并写入一个file-like Object ''' with open('dump.txt','wb') as f: pickle.dump(d,f) ''' pickle.load()方法从一个file-like Object中直接反序列化出对象 ''' with open('dump.txt','rb') as f: d=pickle.load(f) print(d)
Json
import json d={'name':'Bob','age':20,'score':88} with open('testJson','w') as f: json.dump(d,f) with open('testJson','r') as f: print(json.load(f))
Json高级进阶
import json d={'name':'Bob','age':20,'score':88} with open('testJson','w') as f: json.dump(d,f) with open('testJson','r') as f: print(json.load(f)) obj = dict(name='小明', age=20) #ensure_ascii=True,值为True,则序列化保存为ascii码,为False,保存为原始编码 s = json.dumps(obj, ensure_ascii=True) print(s) #一般情况下,我们会序列化类对象 class student(object): def __init__(self,name,age,score): self.name=name self.age=age self.score=score s=student('wangxy',20,88) ''' json.dumps(s)直接序列化对象会输出, raise TypeError(repr(o) + " is not JSON serializable") TypeError: <__main__.student object at 0x7fa705cf05f8> is not JSON serializable ''' #dump和dumps方法中的可选参数default就是把任意一个对象变成一个可序列为JSON的对象 def studentToDict(stu): return { 'name':stu.name, 'age':stu.age, 'score':stu.score } with open('classToJson','w') as f: json.dump(s,f,default=studentToDict) #将json反序列化为类对象实例 def dictToStudent(d): return student(d['name'],d['age'],d['score']) with open('classToJson','r') as f: print(json.load(f,object_hook=dictToStudent)) #通常情况下,class类都有一个__dict__,它就是dict,用来存储实例变量, print(json.dumps(s,default=lambda obj:obj.__dict__))
输出:
{'name': 'Bob', 'score': 88, 'age': 20}
{"name": "\u5c0f\u660e", "age": 20}
<__main__.student object at 0x7f7ac4a906d8>
{"name": "wangxy", "age": 20, "score": 88}