pickle 是一个用户来序列化的模块
序列化是什么?
指的是将内存中的数据结构转化为一种中间格式 并存储到硬盘上
反序列化指的是什么?
将硬盘上存储的中间格式数据在还原为内存中的数据结构
为什么要序列化?
就是为了将数据持久存储
之前学过的文件的中间格式也能完成持久化存储 但是操作起来非常麻烦
pickle 模块的主要功能:
dump
load
dumps
loads
dump是序列化
load是 反序列化
不带s的是帮你封装write read 更方便
load 函数可以多次执行 每次load 都是往后在读一个对象 如果没有了就抛出异常
Ran out of input
import pickle
# 用户注册后得到的数据
name = "高跟"
password = "123"
height = 1.5
hobby = ["吃","喝","赌","飘",{1,2,3}]
# with open("userdb.txt","wt",encoding="utf-8") as f:
# text = "|".join([name,password,str(height)])
# f.write(text)
# pickle支持python中所有的数据类型
user = {"name":name,"password":password,"height":height,"hobby":hobby,"test":3}
# 序列化的过程
# with open("userdb.pkl","ab") as f:
# userbytes = pickle.dumps(user)
# f.write(userbytes)
# 反序列化过程
# with open("userdb.pkl","rb") as f:
# userbytes = f.read()
# user = pickle.loads(userbytes)
# print(user)
# print(type(user))
#
#dump 直接序列化到文件
# with open("userdb.pkl","ab") as f:
# pickle.dump(user,f)
# #load 从文件反序列化
with open("userdb.pkl","rb") as f:
user = pickle.load(f)
print(user)
print(pickle.load(f))
print(pickle.load(f))
print(pickle.load(f))
# def myload(filename):
# with open(filename,"rb") as f:
# return pickle.load(f)