Serialization Implementation Method:
#不实用模块 # info ={# ' name ': ' Alex ', # ' age ': 22##}# f = open ("Test.text", "W") # F.write (str (info)) # # f.close () #json Serialization simple data type # import json## info ={# ' name ': ' Alex ', # ' age ': 22##}# f = open ("Test.text", "W") # F.write (Json.dumps ( Info) # f.close () #python会跟JAVA, C language interaction, which requires an intermediate interactive language---json, can handle a simple data type # import json# def sayhi (name): # Print (" Hello, ", name) # # info ={# ' name ': ' Alex ', # ' age ': 22,# ' func ': sayhi##}# f = open (" Test.text "," W ") # F.write ( Json.dumps (info)) #报错, the function is not serializable import Pickle#pickle can serialize all data types in Python def sayhi (name): print ("Hello,", name) info = { ' name ': ' Alex ', ' age ': $, ' func ': sayhi}f = open ("Test.text", "WB") F.write (Pickle.dumps (info))
Deserialize the appropriate method:
# f = open ("Test.text", "R") # data = eval (F.read ()) # f.close () # # print (data[' age ') # import json## f = open ("Test.text", "R" # data = Json.loads (F.read ()) # # Print (data[' age ') #pickle只能在Python语言内部使用import pickle#f the entire data object to deserialize def sayhi (name): print ("Hello,", name) print ("Hello2,", name) F =open ("Test.text", "RB") Data =pickle.loads (F.read ()) #data = Pickle.load (f) Print (data["func"] (' Alex ')
python3.x can be json.dumps multiple times, but only once json.loads, it is recommended that each program only once json.dumps, once json.loads
Import jsoninfo ={ ' name ': ' Alex ', ' age ': 22}f = open ("Test.text", "W") F.write (Json.dumps (info)) info[' age ']= 21f.write (Json.dumps (info)) F.close ()
Pickle.dumps and Pickle.dump;pickle.loads and Pickle.load
Import Pickle#pickle can serialize all data types in Python def sayhi (name): print ("Hello,", name) info ={ ' name ': ' Alex ', ' Age ': ' func ': sayhi}f = open ("Test.text", "WB") Pickle.dump (info,f) #f. Write (Pickle.dumps (info)) F.close ()---- ------------------------------------------------------------#pickle只能在Python语言内部使用import pickle#f Deserialization of the entire data object Def Sayhi (name): Print ("Hello,", name) print ("Hello2,", name) F =open ("Test.text", "RB") Data =pickle.loads ( F.read ()) #data =pickle.load (f) Print (data["func"] (' Alex ')
Python Learning path: Son and Pickle serialization