Python pickle
Pickle模块作用是持久化的储存数据。
经常遇到在Python程序运行中得到了一些字符串、列表、字典等数据,想要长久的保存下来,方便以后使用,而不是简单的放入内存中关机断电就丢失数据。python模块大全中的Pickle模块就派上用场了,它可以将对象转换为一种可以传输或存储的格式。
Pickle模块提供了四个功能:dumps、dump、loads、load
他们之间的区别:
dumps,loads 还需要使用write,read 读写数据
dump,load 直接帮你 write,read
一、Pickle对象串行化
Pickle模块将任意一个Python对象转换成一系统字节的这个操作过程叫做串行化对象。
二、Pickle与CPickle对比
前者是完全用Python来实现的模块,这个CPickle是用C来实现的,它的速度要比pickle快好多倍,一般建议如果电脑中只要有CPickle的话都应该使用它。
三、Pickle & Json 比较: Json无法处理Class,但是可以处理def
import pickle,json
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
def show(self):
print("self.name:",self.name)
print("self.age:",self.age)
aa = Person("Vincen",22)
aa.show()
with open("a.txt","wb") as f:
json.dump(aa,f)
# pickle.dump(aa,f,0)
with open("a.txt","rb") as f:
bb = json.load(f)
# bb = pickle.load(f)
bb.show()
# pickle可以正常处理Class ,json会报错“TypeError: <__main__.Person object at 0x004AEC70> is not JSON serializable”
#示例二,图片、元组序列化
import pickle
from PIL import Image
im = Image.open("aa.jpg")
tuple1 = ("ceshi",1,3.1415,[1,2,3,4])
with open("results.pkl","wb") as f:
pickle.dump(im,f)
pickle.dump(tuple1,f)
with open("results.pkl","rb") as f:
im2 = pickle.load(f)
tuple2 = pickle.load(f)
list2 = pickle.load(f)
print(im2,tuple2)
print(type(im2),type(tuple2))
Image._show(im2)

浙公网安备 33010602011771号