Python:序列化

# 仅仅支持列表、字典、字符串、数字
import json
# 几乎支持python中所有的数字类型
import pickle
#
import shelve

# dumps  loads
dic = {'aaa': 'bbb', 'ccc': 'ddd'}
str_dic = json.dumps(dic)
print(dic)
# 从dic转换到str
print(str_dic, type(str_dic))  # str
# 写入文件中
with open('json_dump', 'w') as f:
    f.write(str_dic)
# 从str转换到dic
ret = json.loads(str_dic)  # dic
print(ret, type(ret))

# dump  load
# 写入文件中
with open('json_dump1', 'w') as f:
    json.dump(dic, f)
# 读取文件
with open('json_dump1', 'r') as f:
    read = json.load(f)
    print(read, type(read))

dic = {1: (12, 3, 4), ('a', 'b'): 4}
pic_dic = pickle.dumps(dic)
print(type(pic_dic))  # bytes
new_dic = pickle.loads(pic_dic)
print(new_dic)


class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age


alex = Student('male', 23)
print(pickle.dumps(alex))  # byte
with open('pickle_demo', 'wb') as f:
    pickle.dump(alex, f)
with open('pickle_demo', 'rb') as f:
    read_pickle = pickle.load(f)
    print(read_pickle.name)

f = shelve.open('shelve_demo')
f['key'] = {'k1': (1, 2, 3), 'k2': 'v2'}
f.close()
f = shelve.open('shelve_demo')
content = f['key']
f.close()
print(content)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值