序列化: 把不能够直接存储在文件中的数据变得可存储,这个过程就是序列化\
反序列化:把文件中的数据内容拿出来,恢复成原来的数据类型,这个过程就是反 序列化
php:
serialize
unserialize
在文件中存储的数据,要么是字符串,要么是字节流
python中,所有的数据类型都可以通过dumps和loads进行序列化和反序列化
lst = [1,2,3]
with open("ceshi2.txt",mode="a+",encoding="utf-8") as fp:
fp.write(lst)
★★★★
dumps不能往直接文件存储,只能转换字节流,dump可以
dumps转换到文件需要两步,首先要先变成字节流,然后通过'wb'模式写进去
dump直接可以在文件里储存
import pickle
#dumps 把任意对象序列化成一个bytes
lst = [1,2,3]
res = pickle.dumps(lst)
print(res)
def func():
print("我是func函数")
res = pickle.dumps(func)
print(res)
it = iter(range(10))
res = pickle.dumps(it)
#loads 把任意bytes反序列化成原来数据
res = pickle.loads(res)
print(res, type(res))
for i in range(3):
res2 = next(res)
print(res2)
#dump 把对象序列化后写入到file-like Object(即文件对象)
dic = {"a":1,"b":2}
with open("ceshi3.txt",mode="wb") as fp:
# dump(要转换的数据,文件对象) ★★★
pickle.dump(dic,fp)
#load 把file-like Object(即文件对象)中的内容拿出来,反序列化成原来数据('rb'模式)
with open("ceshi3.txt",mode="rb") as fp;
res = pickle.load(fp)
print(res , type(res))
dic = {"a":1,"b":2}
str_bytes = pickle.dumps(dic)
print(str_bytes)
with open("ceshi4.txt",mode="wb") as fp:
fp.write(str_bytes)
with open("ceshi4.txt",mode="rb") as fp:
str_bytes = fp.read()
dic = pickle.loads(str_bytes)
print(dic,type(dic))
所有的编程语言都能够识别的数据格式叫做json,是字符串
能够通过json序列化成字符串的有如下类型:(int float bool str list tuple dict None)
pickle 序列化成字节流
json 序列化成字符串
import json
dic = {"name":"王振","age":30,"classroom":"python30","family":["爸爸","妈 妈","哥哥","姐姐"]}
res =json.dumps(dic,ensure_ascii=False , sort_keys=True)
print(res , type(res))
dic = json.loads(res)
print(dic , type(dic))
dic = {"name":"王振","age":30,"classroom":"python30","family":["爸爸","妈 妈","哥哥","姐姐"]}
with open("ceshi5.json",mode="w",encoding="utf-8") as fp:
# dump(要转换的数据,文件对象)
json.dump(dic,fp,ensure_ascii=False)
with open("ceshi5.json",mode="r",encoding="utf-8") as fp:
dic = json.load(fp)
print(dic, type(dic))
json 可以连续dump , 不可以连续load (load是一次性拿出所有数据进行反序列 化,容易出错)
可以使用loads来解决
dic1 = {"a":1,"b":2}
dic2 = {"c":3,"d":4}
with open("ceshi6.json",mode="w",encoding="utf-8") as fp:
json.dump(dic1,fp)
fp.write("\n")
json.dump(dic2,fp)
fp.write("\n")
with open("ceshi6.json",mode="r",encoding="utf-8") as fp:
dic = json.load(fp)
print(dic)
with open("ceshi6.json",mode="r",encoding="utf-8") as fp:
#文件对象是迭代器,一次迭代一行
for i in fp:
dic = json.loads(i)
print(dic)
import pickle
"""
pickle 可以连续dump , 可以连续load
"""
dic1 = {"a":1,"b":2}
dic2 = {"c":3,"d":4}
with open("ceshi7.pkl",mode="wb") as fp:
pickle.dump(dic1,fp)
pickle.dump(dic2,fp)
with open("ceshi7.pkl",mode="rb") as fp:
dic = pickle.load(fp)
print(dic)
dic = pickle.load(fp)
print(dic)
print("<=====>")
"""try .. except .. 抑制报错 如果try代码块里面有问题,就执行except中的代 码"""
"""
try:
把有问题的代码放进来
except:
如果出现异常执行这个分支的代码块.
"""
try:
with open("ceshi7.pkl",mode="rb") as fp:
while True:
dic = pickle.load(fp)
print(dic)
except:
pass
“”"
(1)json序列化之后的数据类型是str,所有编程语言都识别,(数据交流)
但是仅限于(int float bool)(str list tuple dict None)
json不能连续load,只能一次性拿出所有数据
(2)pickle序列化之后的数据类型是bytes, (存储转换)
所有数据类型都可转化,但仅限于python之间的存储传输.
pickle可以连续load,多套数据放到同一个文件中
“”"