序列化模块2 pickle

import pickle

# dump的结果是bytes,dump用的f文件句柄需要以wb的形式打开,load所用的f是'rb'模式
# 支持几乎所有对象的序列化
# 对于对象的序列化需要这个对象对应的类在内存中
# 对于多次dump/load的操作做了良好的处理

dic = {1:(1,2,3),('a','b'):4}
#序列化
pic_dic = pickle.dumps(dic)
print(pic_dic)  # bytes类型
#反序列化
new_dic = pickle.loads(pic_dic)
print(new_dic)

 

# pickle支持几乎所有对象

class Student:
    def __init__(self,name,age):
        self.name = name
        self.age = age
# 实例化一个对象
ben = Student('ben',13)
pic_ben = pickle.dumps(ben) # 序列化对象
print(pic_ben)
new_ben = pickle.loads(pic_ben)  #反序列化对象
print(new_ben.name)  # 对象.属性
print(new_ben.age)   # 对象.属性

 

# 处理文件

class Teacher:
    def __init__(self,name,age):
        self.name = name
        self.age = age
# 实例化一个对象
carl = Teacher('张三',38)

with open('pic_demo','wb') as f1:
    pickle.dump(carl,f1)   # 序列化对象

with open('pic_demo','rb') as f2:
    ret = pickle.load(f2) # ret是反序列化后得到的对象
    print(ret.name)  #对象调用属性 name


# 对于多次dump/load的操作做了良好的处理

with open('pic_demo','wb') as f1:
    pickle.dump('赵六',f1)
    pickle.dump({'k1':'vi'},f1)
    pickle.dump((1,2,3),f1)
    pickle.dump(['a','b',[1,2,('qq',1)]],f1)

with open('pic_demo','rb') as f1:
    # print(pickle.load(f1))
    # print(pickle.load(f1))
    # print(pickle.load(f1))
    # print(pickle.load(f1))
    # print(pickle.load(f1))
    # print(pickle.load(f1))
    # 超出范围,报错,EOFError: Ran out of input
    #不知道里面有多少内容,用while 循环
    while True: # 异常判断
        try:
            print(pickle.load(f1))
        except EOFError:
            break

 

posted @ 2018-08-09 18:02  Niuli'blog  阅读(166)  评论(0编辑  收藏  举报