pickle 序列化模块

序列化:   把不能够直接存储的在文件中的数据变得可存储

反序列化 :把存储的数据拿出来恢复成原来的数据类型 

需要配合文件操作   使用 dump 和 load

不需要配合文件操作 使用 dumps 和 loads

import pickle

dump  把对象序列化后写入到file-like Object(即文件对象)

lst = [1,12,3,4]
with open("ceshi1.txt",mode="wb") as fp:
    pickle.dump(lst,fp)

load  把file-like Object(即文件对象)中的内容拿出来,反序列化成原来数据

with open("ceshi1.txt",mode="rb") as fp:
    res = pickle.load(fp)
print(res,type(res))

dumps 把任意对象序列化成一个bytes

def func():
    print("我是func函数 ... ")
res = pickle.dumps(func)
print(res)

loads 把任意bytes反序列化成原来数据

func = pickle.loads(res)
func()

序列化迭代器

from collections import Iterator,Iterable
it = iter(range(10))
print(isinstance(it,Iterator))
res1 = pickle.dumps(it)
print(res1)

反序列化

it = pickle.loads(res1)
print(next(it))

使用dumps 和 loads 将数据存储到文件中

with open("ceshi1.txt",mode="wb") as fp:
    res1 = pickle.dumps(it)
    fp.write(res1)

with open("ceshi1.txt",mode="rb") as fp:
    res = fp.read()
    it = pickle.loads(res)
print(next(it))
print(next(it))
print(next(it))

 

posted @ 2021-04-13 09:54  你也想起舞吗ovo  阅读(50)  评论(0编辑  收藏  举报