pickle 模块

pickle模块主要功能:

  dump  ———— 序列化

  load  ————— 反序列化

  dumps

  loads

  ps: 不带s的是帮你封装write  read  更方便

    load 函数可以多次执行  每次load 都是往后再读一个对象,如果没有了就抛出异常 Run out of input

 

pickle 模块实例: 

 

import pickle
# 用户注册后得到的数据
name = "高跟"
password = "123"
height = 1.5
hobby = ["吃","喝","赌","飘",{1,2,3}]

# 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))

  

 

 

 

 

 

 

 

posted @ 2018-10-17 15:22  萤huo虫  阅读(197)  评论(0编辑  收藏  举报