JSON & Pickle Module (serialized)
Two modules for serialization
- JSON, used to convert between string and Python data types
- Pickle for conversion between Python-specific types and Python data types
The JSON module provides four functions: dumps, dump, loads, load
The Pickle module provides four functions: dumps, dump, loads, load
Dumps and dump differences:
Pickle.dump (info,f) #print (Pickle.dumps (info)) #f. Write (Pickle.dumps (info))
Loads and load differences:
Data_from_atm=pickle.load (f) #data_from_atm =pickle.loads (F.read ())
Pickle (unique in Python, supports all Python data types)
Convert a dictionary to a string
1 ImportPickle2F= Open ("User_acc.txt","WB")3 4info={5 "Alex":"123",6 "Jack":"4444"7 }8 9 F.write (Pickle.dumps (info))TenF.close ()Serialization of
Convert a string to a dictionary
Import Picklef= open ("user_acc.txt","RB") data_from_ ATM=pickle.loads (f.read ())print(DATA_FROM_ATM)
deserialization
JSON (common to all languages, support dictionaries, lists, tuples)
Convert a dictionary to a string
1 ImportPickle2 ImportJSON3F= Open ("User_acc.txt","W")4 5info={6 "Alex":"123",7 "Jack":"4444"8 }9 Ten F.write (Json.dumps (info)) OneF.close ()Serialization of
Convert a string to a dictionary
1 Import Pickle,json 2 f= open ("user_acc.txt","R")3 4 data_from_atm=json.loads (F.read ())56print(data_ FROM_ATM)
deserialization
Instance:
Python Learning Notes-basic "Fifth Week"--json & pickle Modules