Pickle模块
Pickle模块
序列化/反序列化模块
import pickle
序列化: 把不能够直接存储在文件中的数据变得可存储
反序列化: 把存储在文件中的数据拿出来恢复成原来的数据类型
文件不能直接存储容器 , 文件只能存储字符串和字节流
dumps 和 loads
最好做偏编码解码的操作
lst = [1,2,3]
res = pickle.dumps(lst)
print(res , type(res)) #out bytes
res2 = pickle.loads(res)
print(res2 , type(res2)) #out list
#迭代器可以序列化么? 可以
it = iter(range(10))
res = pickle.dumps(it)
print(res , type(res)) #out bytes
"""
区分于字符串写入二进制文件的bytes的编码和解码
data = "中文".encode("utf-8")
print(data, type(data)) # 输出:b'\xe4\xb8\xad\xe6\x96\x87' <class 'bytes'>
res = data.decode("utf-8")
print(res, type(res)) # 输出:中文 <class 'str'>
"""
# dumps 和 loads 对文件进行写入读取字节流操作 --> 实现与dump 和 load模式
# 写入字节流
with open("lianxi2.txt",mode="wb") as fp:
lstBytes = pickle.dumps(lst)
fp.write(lstBytes)
# 读取字节流
with open("lianxi2.txt",mode="rb") as fp:
lstBytes = fp.read()
res = pickle.loads(lstBytes)
print(res , type(res2)) # out type is lst
dump 和 load
最好做实现对文件操作的功能
#dump 把对象序列化后写入到file-like Object(即文件对象)
lst = [1,2,3]
with open("lianxi1.txt",mode="wb") as fp:
pickle.dump(lst,fp) # 序列化存入文件对象
#load 把file-like Object(即文件对象)中的内容拿出来,反序列化成原来数据
with open("lianxi1.txt",mode="rb") as fp:
res2 = pickle.load(fp) # 反序列归还
print(res2 , type(res2)) #out type is lst

浙公网安备 33010602011771号