Python之pickle

Posted Fate0729

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python之pickle相关的知识,希望对你有一定的参考价值。

Pickle模块可以序列化对象并保存到磁盘中,并在需要的时候读取出来,任何对象都可以执行序列化操作。在机器学习中,我们常常需要把训练好的模型存储起来,这样在进行决策时直接将模型独处,而不需要重新训练模型,这样就大大节约了时间。

pickle模块常用函数

dump(obj,file,[,protocol]) 将obj对象序列化存入已经打开的file中
load(file) 将file中的对象序列化读出
dumps(obj,[,protocol]) 将obj对象序列化为string形式,而不是存入文件中
loads(string) 从string中读出序列化前的obj对象

示例

#coding=utf-8

import pickle

datalist = [[1, 1, yes],  
           [1, 1, yes],  
           [1, 0, no],  
           [0, 1, no],  
           [0, 1, no]]  
           
datadict = { 0: [1, 2, 3, 4],  
            1: (a, b),  
            2: {c:yes,d:no}}  

with open("pickle_test.txt","wb") as writefp:
    pickle.dump(datalist, writefp)
    pickle.dump(datadict, writefp)
  
with open("pickle_test.txt", "rb") as readfp:
    data1 = pickle.load(readfp)
    data2 = pickle.load(readfp)
    print (data1)
    print (data2)

p = pickle.dumps(datalist)  
print( pickle.loads(p) )  
p = pickle.dumps(datadict)  
print( pickle.loads(p) ) 

  >>> [[1, 1, ‘yes‘], [1, 1, ‘yes‘], [1, 0, ‘no‘], [0, 1, ‘no‘], [0, 1, ‘no‘]]
  >>> {0: [1, 2, 3, 4], 1: (‘a‘, ‘b‘), 2: {‘c‘: ‘yes‘, ‘d‘: ‘no‘}}
  >>> [[1, 1, ‘yes‘], [1, 1, ‘yes‘], [1, 0, ‘no‘], [0, 1, ‘no‘], [0, 1, ‘no‘]]
  >>> {0: [1, 2, 3, 4], 1: (‘a‘, ‘b‘), 2: {‘c‘: ‘yes‘, ‘d‘: ‘no‘}}

  dump和load相比dumps和loads还有另外一种能力:dump()函数能一个接着一个的将几个对象序列化存储到同一个文件中,随后调用load()来以同样的顺序反序列化读出这些对象



以上是关于Python之pickle的主要内容,如果未能解决你的问题,请参考以下文章

python之pickle模块

Python之pickle

python常用模块之json和pickle模块

python之函数二 | pickle模块

python之json&pickle

python3之序列化(pickle&json)