Serialization of 14.1
Example 1:
#! Author:lanhan
#把字典的内存数据类型通过字符串存到硬盘上 (json.dumps) , only strings, lists, dictionaries, etc. are processed
Import JSON
info = {
' name ':' Lanhan ',
' age ': 22
}
f = open ("test.txt","W")
Print (Json.dumps (info))
F.write (Json.dumps (info))
F.close ()
Example 2: pickle can handle complex, such as functions
Import Pickle
def Sayhi (name):
Print ("Hello", name)
info = {
' name ':' Lanhan ',
' age ': 22,
' func ': Sayhi
}
f = open ("test.txt","WB")
F.write (Pickle.dumps (info))
Example 3:
Import JSON
def Sayhi (name):
Print ("Hello", name)
info = {
' name ':' Lanhan ',
' age ': 22
}
f = open ("test.txt","W")
F.write (Json.dumps (info))
info[' age '] = 21
F.write (Json.dumps (info))
F.close ()
14.2 Deserialization
Example 1:
#! Author:lanhan
#把硬盘的数据类型恢复到内存中 (json.loads) , only strings, lists, dictionaries, etc. are processed
Import JSON
f = open ("test.txt","R")
data = Json.loads (F.read ())
F.close ()
Print (data["age"])
Example 2:pickle can handle complex, such as functions
# #pickle
Import Pickle
def Sayhi (name):
Print ("Hello", name)
Print ("Hello2", name)
f = open ("test.txt","RB")
data = Pickle.load (f) ###==== #data = Pickle.loads (F.read ())
Print (data["func"] ("Lanhan"))
Example 3:
#! Author:lanhan
#c错误的, indicating that there are multiple states can dump multiple times, not multiple loads, that is, there are multiple states dump multiple files, dump once, load once
Import JSON
f = open ("test.txt","R")
for line in F:
Print (Json.loads (line))
Print (data)
Python route -14. Json & Pickle Data serialization