Python's pickle module implements basic data sequence and deserialization. Through the serialization of the Pickle module we are able to save the object information running in the program to a file, to store it permanently, and through the Pickle module's deserialization, we are able to create from the file the last object saved by the program.
First, Pickle object serialization
Pickle module The process of converting any Python object into a system byte is called a serialized object.
Ii. comparison of Pickle and cpickle
The former is completely in Python to implement the module, the Cpickle is implemented with C, it is faster than pickle many times faster, generally recommended if the computer as long as there is cpickle should use it.
Third, the dump () method of the Pickle module
There are 2 common function methods in the Pickle module, one called dump ()and the other called load ().
The third part, Pickle.dump () method:
The syntax for this method is:pickle.dump (object, file, [Usage Protocol])
Hint: The data to be persisted "object", Save to "file", use 3 kinds, index 0 is ascii,1 is old-fashioned 2, 2 is the new 2 binary protocol, the difference is in the latter more efficient. By default, the dump method uses 0 to do the protocol.
Iv. Load method of the Pickle module
The load () method acts just as opposed to the dump () method above, which is serialized data, which is deserialized.
Syntax: pickle.load (file)
Tip: From the file, read the strings, deserialize them into Python's data objects, and manipulate them as you would normally manipulate the data types.
#使用pickle模块将数据对象保存到文件Import pickledata1 = {' A ': [1, 2.0, 3, 4+6j], ' B ': (' string ', U ' Unicode string '), ' C ': None}selfref_list = [1, 2, 3]selfref_list.append (selfref_list) output = open (' Data.pkl ', ' WB ') # Pickle dictionary usi NG Protocol 0.pickle.dump (data1, Output) # Pickle the list using the highest protocol available.pickle.dump (Selfref_list, O Utput,-1) output.close ()
#使用pickle模块从文件中重构python对象Import pprint, picklepkl_file = open (' data.pkl ', ' RB ') data1 = Pickle.load (pkl_file) Pprint.pprint (data1) data2 = Pickle.load (pkl_file) pprint.pprint (data2) pkl_file.close ()
Python data persistence: basic use of the Pickle module