pickling有一个更常用的叫法是serialization,它是指把python对象转化成字节流byte stream, unpickling就是把byte stream转换成对象。python的pickle函数包中的pickle.dump,可以帮助把对象以字节流的形式储存在pickle文件,等到用时pickle.load可以帮助载入。
在数据科学中可以巧用它来存在数据对象,数据类型可以是如string, int, numpy.array, dict, tuple, etc. 真是爽爆了。简单的例子如下:
# 存储字符串. import pickle longstring="Iamaverylongstring" #用pickle.dump存储数据 pickle.dump(longstring,open("longstringfile.pkl","w")) #用pickle.load提取 string1=pickle.load(open("longstringfile.pkl")) Print string1 # 存储numpy.array import numpy list1=[[1,2,3],[2,4,6]] anp1=numpy.array(list1) print np1 pickle.dump(anp,open("npfile.pkl","w")) np2=pickle.load(open("npfile.pkl")) print np2 print type(np2)
结果如下:
Iamaverylongstring
[[1 2 3]
[2 4 6]]
[[1 2 3]
[2 4 6]]
<type 'numpy.ndarray'>