First, the definition
Serialization refers to removing an object from memory to write to a store, such as a TXT file, in reverse sequence.
Second, the application scenario
- Cross-platform data transfer;
- Keep changes to the object the last time you run the program
III. Modules and functions
1. JSON
Dumps (), Dump () (serialized)
Loads (), load () (deserialization)
2. Pickle
Dumps (), Dump () (serialized)
Loads (), load () (deserialization)
Iv. Application Cases
1. Pickle
1 ImportPickle2 3info = {"Lyrics":"Geci",4 "Song":"gequ",5 " Time": 89}6 7With open ("Pickling.txt","WB") as F:#Serialization of8 F.write (Pickle.dumps (info))9 TenWith open ("Pickling.txt","RB") as F:#deserialization One Print(Pickle.load (f))
The above code first converts the dictionary info to an object of type Str and then writes to the TXT file, where line 8th can be replaced with
Pickle.dump (INFO,F)
The two implementations are the same, except that dums directly serializes the object and writes it to the TXT file. The result of writing a file is a bunch of things that you don't understand, as follows:
But this is not an error, not a letter, and finally the load () function to deserialize it after the console output is:
Similarly, the loads () function can replace the load function. As follows:
1 print(Pickle.loads (F.read ()))
2. JSON
Pickle is unique to Python, and JSON enables data conversion and transmission in different programming languages. Data transfer in different programming languages requires the conversion of their data types to a common standard type, and JSON is one of them. The corresponding relationship between the JSON data type and the Python data type is as follows:
The use of JSON is roughly the same as pickle, except that the read-write mode of JSON is not "WB" and "RB", but "W" and "R" when reading and writing files.
Python serialization and deserialization of--json and pickle