Two modules for serialization:
JSON: Used to convert between string and python number types
Oickle: Converting between Python-specific types and Python data types
The JSON, pickle module provides four functions: dumps, dump, loads, load
Use Json&pickle to convert to a string to write to a file
1 ImportJSON2 ImportPickle3 4 defSayhi (name):5 Print("Hello,", name)6 7info = {8 "name":"GUOXF",9 " Age":" -",Ten "Sex":"nan", One "func": Sayhi A } - -Info1 = { the "name":"GUOXF", - " Age":" -", - "Sex":"nan", - #"func": Sayhi + } - +f = open ("a.txt","WB") A #Json.dump (INFO1) # The two are exactly equal Json.dumps (INFO1) atPickle.dump (info, f)#both are exactly equal F.write (Pickle.dumps (info)) -F.close ()
Use Json&pickle to convert a string in a file into a dictionary read
1 ImportJSON2 ImportPickle3 4 defSayhi (name):5 Print("Hello,", name)6 7f = open ("a.txt","RB")8 #data = Json.loads (F.read ())9 #data = Pickle.loads (F.read ())Tendata =pickle.load (f) One Print(data) A - f.close () - the Print(data["func"]("GXF"))
The Json&pickle of Python