序列化模块
- 序列化——将内存数据转换为字符串
- 反序列化——将字符串转换为内存数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| # 序列化 data = { "infos":[ {"name":"张飞","life":100,"arm":"丈八蛇矛"}, {"name":"关羽","life":110,"arm":"青龙偃月刀"} ] }
f = open("info.txt",mode="w",encoding="utf-8") f.write(str(data))
# ----------------------------------------------------------------
# 反序列化 f = open("info.txt",mode="r",encoding="utf-8") strinfo = f.read() info = eval(strinfo) print(info)
|
常用模块
序列化模块知识点总结
json 模块
- json.dumps(序列化对象:如字典)
- json.loads(字符串)
- json.dump(数据类型,文件)
- json.load(文件)
注意点
1 2 3 4 5 6
| f = open('fff',encoding='utf-8') res = json.load(f) res = json.load(f) f.close()
# 不要尝试多次 dump或者 多次load
|
- python2中多次dump文件里会帮你自动换行
- python3里直接禁止了你多次调用dump/load这些方法
结论:无论何时都不要多次调用在一个文件句柄里多次调用 dump和load
pickle 模块
- pickle.dumps(序列化对象:如字典)
- pickle.loads(字符串)
- pickle.dump(数据类型,文件)
- pickle.load(文件)
它与json方法差不多,唯一区别就是序列化的内容是bytes你看不懂的内容(二进制的)
json 模块和 pickle 模块区别
- json 仅支持序列化 str / int / tuple / list / dict
- pickle 支持python里所有数据类型(只能在python里)
- load dump 都仅能用一次
shelve 模块
跟前俩模块的区别就是:json、pickle只能load /dump 一次,但是shelve支持多次
- 原理是对pickle进行了封装,python里独有的,并且顺序不会出错
- 核心就是key/value
序列化到文件里
1 2 3 4
| import shelve f = shelve.open('shelve_file') f['key'] = {'int':10, 'float':9.5, 'string':'Sample data'} #直接对文件句柄操作,就可以存入数据 f.close()
|
反序列化
1 2 3 4 5 6 7 8 9
| import shelve f1 = shelve.open('shelve_file') existing = f1['key'] #取出数据的时候也只需要直接用key获取即可,但是如果key不存在会报错 # 推荐使用 get()获取字段 这样如果key不存在返回 None xx = f1['xxx'] print(xx) # None
f1.close() print(existing)
|
关于修改你肯定会这样遇到问题?为啥修改不了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import shelve f1 = shelve.open('shelve_file') f1['names'] = ["a","b","c","d","e"] f1['names'][2] = "ccc" f1.close()
f2 = shelve.open('shelve_file') print(f2["names"])
-------------------------- 正确答案是 整体修改 --------------------------
f1['names'] = ["a","b","c","d","e"] # f1['names'][2] = "ccc" f1['names'] = ["a","b","ccc","d","e"]
|