Home >Backend Development >Python Tutorial >Python object—Pickle pickling
In Python, if we have some objects that need to be stored persistently without losing the type and data of our objects, we need to serialize these objects. After serialization, when we need to use them, we can restore them to their original values. data. This process of serialization is called pickle. The recovery process is called reverse pickle
There are two forms of pickling objects, one is to serialize the object, and the other is to serialize the object by storing it in a file
There is the pickle module in python. We just need to import it.
# pickle腌制 import pickle #导入pickle模块 #dumps(object)将对象序列化 lista = ["mingyue","jishi","you"]#这个列表就是一个对象,我们要将这个列表对象序列化 listb = pickle.dumps(lista)#pickle模块里面的dumps()函数用于将对象序列化,然后将经过序列化的列表赋给listb print listb
输出为: (lp0 S'mingyue' p1 aS'jishi' p2 aS'you' p3 a.
#load(string)将对象原样恢复,并且对象类型也恢复了原来的格式
listc = pickle.loads(listb)
print listc
#dump(object, file)将对象存储到文件里面序列化,这里是dump,与前面的dumps相差了一个s f1 = file('1.pkl', 'wb') pickle.dump(group1, f1, True) f1.close()
#load(object, file)存储在文件里面的数据恢复 f2 = file('1.pkl', 'rb') t = pickle.load(f2) print t f2.close()
输出为: ('bajiu', 'wen', 'qingtian')