常用模块02
1. 什么是序列化
- 在python中存在三种序列化的方案
- pickle. 可以将我们python中的任意数据类型转化成bytes并写入到⽂件中. 同样也可以把文件中写好的bytes转换回我们python的数据. 这个过程被称为反序列化
- shelve. 简单另类的一种序列化的方案.
- json. 将python中常用的字典, 列表转化成字符串. 是目前前后端数据交互使用频率最高的一种数据格式.
2. pickle(重点)
python对象写入到文件中的一种解决⽅案.但是写入到文件的是bytes
import pickle
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
def catchMouse(self):
print(self.name, "抓老鼠")
c = Cat("jerry", 18)
bs = pickle.dumps(c) # 序列化一个对象.
print(bs) # ⼀堆⼆进制. 看不懂
cc = pickle.loads(bs) # 把二进制反序列化成我们的对象
cc.catchMouse() # 猫依然是猫. 还可以抓老鼠
- pickle中的dumps可以序列化一个对象.
- loads可以反序列化一个对象.
- dump还可以直接 把一个对象写入到文件中
3. shelve
shelve提供python的持久化操作
import shelve
shelf = shelve.open("sylar")
# shelf["jay"] = "周杰伦"
print(shelf['jay'])
shelf.close()
s = shelve.open("sylar")
# s["jay"] = {"name":"周杰伦", "age":18, "hobby":"哄小孩"}
print(s['jay'])
s.close()
下面是测试
s = shelve.open("sylar")
s['jay']['name'] = "胡辣汤" # 尝试改变字典中的数据
s.close()
s = shelve.open("sylar")
print(s['jay']) # 并没有改变
s.close()
解决方案:
s = shelve.open("sylar", writeback=True)
s['jay']['name'] = "胡辣汤" # 尝试改变字典中的数据
s.close()
s = shelve.open("sylar")
print(s['jay']) # 改变了.
s.close()
writeback=True可以动态的把我们修改的信息写入到文件中
s = shelve.open("sylar", writeback=True)
del s['jay']
s.close()
s = shelve.open("sylar")
print(s['jay']) # 报错了, 没有了
s.close()
s = shelve.open("sylar", writeback=True)
s['jay'] = "周杰伦"
s['wlj'] = "王力宏"
s.close()
s = shelve.open("sylar")
for k in s: # 像字典那样遍历
print(k)
print(s.keys()) # 拿到所有key的集合
for k in s.keys():
print(k)
for k, v in s.items(): # 像字典一样操作
print(k, v)
s.close()
4. json(重点)
# ----- loads 转换字符串到json ----------------
s1 = '{"1":"毒液","2":"雷神","3":"海王","4":false,"5":null}'
d = json.loads(s1)
print(d)
# --------------字符串 转 字典 进文件----------------
dic1 = {"1":"毒液","2":"雷神","3":"海王","4":False,"5":None,"6":{"想看":"没钱","能看":"没时间"}}
f = open("du.json",mode="w",encoding="utf-8")
json.dump(dic1,f,ensure_ascii=False,indent=4)
f = open("du.json",mode="r",encoding="utf-8")
d = json.load(f)
print(d)
# -------------json 函数传入返回 字典形式---------
class Man():
def __init__(self,firstname,lastname):
self.firstname = firstname
self.lastname = lastname
Person = Man("海格力斯","王五")
def func(obj):
return {
"first":obj.firstname,
"last":obj.lastname
}
s = json.dumps(Person,default=func,ensure_ascii=False)
print(s)
#-----------------字符串 字典 返回 对象------------
class Man():
def __init__(self,firstname,lastname):
self.firstname = firstname
self.lastname = lastname
dic = '{"firstname":"海格力斯","lastname":"王五"}'
def func(dic):
return Man(dic["firstname"],dic["lastname"])
s = json.loads(dic,object_hook=func)
print(s.firstname)