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.
Basic interface:
Pickle.dump (obj, file, [, Protocol])
Note: Save the object, obj, to file.
Protocol is the protocol version used for serialization, the 0:ASCII protocol, the serialized object is represented by printable ASCII code, 1: The old binary protocol, and the new binary protocol introduced by version 2:2.3, which is more efficient than the previous ones. where protocols 0 and 1 are compatible with older versions of Python. The default value for protocol is 0.
File: Object to which the class files are saved. File must have a write () interface, file can be an open with a ' W ' method or an Stringio object or any other object that implements the write () interface. If protocol>=1, the file object needs to be opened in binary mode.
Pickle.load (file)
Note: Reads a string from file and reconstructs it as the original Python object.
File: Class files object with Read () and ReadLine () interfaces.
A Simple Code
#使用pickle模块将数据对象保存到文件
import Pickle
data1 = {' A ': [1, 2.0, 3, 4+6j],
' C ': None}
Br>selfref_list = [1, 2, 3]
selfref_ List.append (selfref_list)
output = open (' Data.pkl ', ' WB ')
# Pickle Dictionary using protocol 0.
pickle.dump (data1, Output)
# Pickle the list using the highest protocol available.
pickle.dump (selfref_list, output,-1)
output.close ()
#使用pickle模块从文件中重构python对象
Import Pprint, pickle
Pkl_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's JSON module provides a very simple way to encode and decode JSON data. Two of the main functions are json.dumps () and Json.loads (), which is much less than the interfaces of other serialization function libraries such as pickle. The following shows how to convert a Python data structure to JSON:
1 2 3 4 5 6 7 8 9 |
import json data = { ‘name‘ : ‘ACME‘ , ‘shares‘ : 100 , ‘price‘ : 542.23 } json_str = json.dumps(data) |
The following shows how to convert a JSON-encoded string back to a python data structure:
1 |
data = json.loads(json_str) |
If you are dealing with files instead of strings, you can use Json.dump () and Json.load () to encode and decode JSON data. For example:
1 2 3 4 5 6 7 |
# Writing JSON data with open ( ‘data.json‘ , ‘w‘ ) as f: json.dump(data, f) # Reading data back with open ( ‘data.json‘ , ‘r‘ ) as f: data = json.load(f) |
Python serialized JSON Pickle