Python object—Pickle pickling

高洛峰
Release: 2016-12-16 11:41:12
Original
1139 people have browsed it

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
Copy after login
输出为:  
(lp0  
S'mingyue'  
p1  
aS'jishi'  
p2  
aS'you'  
p3  
a.
Copy after login
#load(string)将对象原样恢复,并且对象类型也恢复了原来的格式
Copy after login
listc = pickle.loads(listb)
Copy after login
print listc
Copy after login
#dump(object, file)将对象存储到文件里面序列化,这里是dump,与前面的dumps相差了一个s  
f1 = file('1.pkl', 'wb')  
pickle.dump(group1, f1, True)  
f1.close()
Copy after login
#load(object, file)存储在文件里面的数据恢复  
f2 = file('1.pkl', 'rb')  
t = pickle.load(f2)  
print t  
f2.close()
Copy after login
输出为:  
('bajiu', 'wen', 'qingtian')
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template