41 json和pickle模块

"""
1、什么是序列化与反序列化
    内存中某一类的数据---------------》特殊的格式
    内存中某一类的数据《---------------特殊的格式
2、为何要序列化
    1、存档:把内存中的数据持久化到硬盘
    2、跨平台交互数据

    在python中:
        存档=》推荐用pickle格式
        跨平台交互=》推荐用json格式
3、如何序列化


"""
# 一:low的序列化与反序列化方式
# 1.序列化
items = ["圣剑", "蝴蝶", "BKB"]

dic_str = str(items)

with open('db.txt', mode='wt', encoding="utf-8") as f:
	f.write(dic_str)

# 2.反序列化
with open('db.txt', mode='rt', encoding='utf-8') as f:
	data = f.read()  # "['圣剑', '蝴蝶', 'BKB']"

	items = eval(data)
	print(items[0])

# 二:json
# 优点:跨平台交互数据
# 缺点:无法识别所有的python数据类型
# 注意:json格式的字符串里不能包含单引号
import json

# 序列化方式一:
t = {"a": 1, "b": 2}  # 字典=======》json格式的字符串:"[1,2,3]"

res = json.dumps(t)
print(res, type(res))

with open("a.json", mode='wt', encoding='utf-8') as f:
	f.write(res)

# json反序列化方式一:
with open("a.json", mode='rt', encoding='utf-8') as f:
	data = f.read()
	dic = json.loads(data)
	print(dic, type(dic))

res = json.loads('{"k1":111}')
print(res['k1'])

# json序列化方式二:
t = {"a": 1, "b": 2}  # 字典=======》json格式的字符串:"[1,2,3]"

with open("b.json", mode='wt', encoding='utf-8') as f:
	json.dump(t, f)

# json反序列化方式二:
with open("b.json", mode='rt', encoding='utf-8') as f:
	dic = json.load(f)
	print(dic, type(dic))

# 三:pickle
# 优点:可以识别所有python类型
# 缺点:只能用于python中,无法跨平台交互
import pickle

s = {1, 2, 3, 4, 5}

res = pickle.dumps(s)
# print(res,type(res))
with open('a.pkl', mode='wb') as f:
	f.write(res)

with open('a.pkl', mode='rb') as f:
	data = f.read()
	s = pickle.loads(data)
	print(type(s))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值