因为想要说的都写在了注释里面,所以直接粘代码(偷个懒,嘻嘻~~)。
# 序列化:把内存中的变量转换成可存储或者传输的过程
#一、python中的序列化方法 pickle 模块,仅可用于python
import pickle
#定义一个dict对象
d = dict(name='Bob',age=20,score=80)
# 序列化
print(pickle.dumps(d)) #直接序列化
#还可序列化到文件
path = r'C:/Users/Lenovo/Desktop/data.txt'
# f = open(path,'wb') #以二进制形式写入
# pickle.dump(d,f)
# f.close()
with open(path,'wb') as f:
pickle.dump(d,f)
#反序列化
# f = open(path,'rb')
# print(pickle.load(f))
# f.close()
with open(path,'rb') as f:
print(pickle.load(f))
# 二、JSON 序列化标准格式
# json模块
import json
d = dict(name='Jarry',age= 21,score=90)
print(json.dumps(d))
with open(path,'w') as f:
json.dump(d,f) #dump方法将dict转换成str格式
#json序列化类
class Student(object):
def __init__(self,name,age,score):
self.name = name
self.age = age
self.score = score
def studentToDict(std):
return {
'name':std.name,
'age':std.age,
'score':std.score
}
s = Student('Marry',18,99)
with open(path,'w') as f:
json.dump(s,f, default=studentToDict)
#反序列化类
def dictToStudent(std):
return Student(std['name'],std['age'],std['score'])
with open(path,'r') as f:
print(json.load(f,object_hook=dictToStudent))