python--序列化

因为想要说的都写在了注释里面,所以直接粘代码(偷个懒,嘻嘻~~)。

# 序列化:把内存中的变量转换成可存储或者传输的过程

#一、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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值