Learning content:
JSON module, pickle module, shelve module
Serialization of JSON modules:
1 ImportJson,pickle2 3info={4 'name':'a',5 ' Age': 34,6 'func':"'7 }8With open ('Text.txt','W') as F:9 #f.write (json.dumps (' Test.txt ')) #新建一文件用于存入序列化的数据TenF.write (Json.dumps (info))#Serialization of
JSON module deserialization (open file from another program):
1 Import Json,pickle 2 with open ('text.txt','r') as F:3 4 fp=json.loads (F.read ())# deserialization 5
#fp =json.load (f) # effect is the same as loads
6 Print ('\033[32;1m%s\033[0m'%fp)
Pickle modules are used in the same way as jsong (unlike Pickle, which can save object formats, such as object properties where functions can exist):
1 deffunc1 ():2 Print('1111111')3Info2={4 'name':'a',5 ' Age': 34,6 'func': Func17 8 }9With open ('Test','WB') as F2:TenF2.write (Pickle.dumps (Info2))#===pickle.dump (INFO2,F2) Effect
Pickle Module Deserialization:
1 def func1 (): 2 Pass 3 4 with open ('test','rb') as F2: 5 c=pickle.load (F2)6 #c=pickle.loads (F2.read ()) #效果与loads一样 78print(c)
Shelve module (equivalent to multiple ldump, and load):
Shelve uses the dictionary of key and vaule to persist data through a file-can persist any Python data format that pickle can support:
1 Importshelve2 3 defFunc_1 (name,age):#Define a function4 Print(name,age)5 6name=['a','b','C','D']#Define a list7age=[1,2,3,4]8 9D=shelve.open ('Test_3.txt')#use shelve to open filesTen One #save individual objects to a file Ad['name']=name -d[' Age']= Age -d['func']=func_1 theD.close ()
Shelve, deserialization:
1 Importshelve2 defFunc_1 (name,age):#defines a function that is the same as the function name stored by shelve3 Print(age)4F=shelve.open ('Test_3.txt')#open files that were previously stored in data5 6name=f['name']#extract the corresponding data name7 Print(name)8 9age=f[' Age']#extract the corresponding data ageTenfunc_1=f['func']#extract the corresponding data func_1 OneFunc_1 (Name,age)#extract the corresponding data
Python 18th day