JSON and pickle modules, two modules for serializationJSON module for conversion between a string and a Python data typePickle Module for conversion between Python-specific types and Python data typesTwo modules, all available with dumps,dump,loads,load 4 functions1 ImportJSON2s ='{"Key1": "Value1", "Key2": "Value2"}'
Two modules for serialization in Python
JSON is used to convert between "string" and "Python Basic data Types"
Pickle for "Python-specific type" and "Python basic data type" to convert between
The JSON module provides four functions: dumps, dump, loads, loa
Json
Conversions between data types for strings and Python
Four functions
Dumps
Dump
Loads
Load
Pickle
Conversion for Python-specific types and Python data types
Four functions
Dumps
Dump
Loads
Load
Shelve
K,v
dumps :import=open("test.text","wb")f.write(json.pickle(info))f.close()Similarly, we can use dump methods instead of dumps methods:You only need tof.write(pickle.dumps(info))Replace pickle.dump(info,f) it with.
Deserialization loads :import pickledef sayhi(name): print("hi"+=open("test.txt","rb"= pickle.loads(f.read())Similarly, we can use load methods instead of loads methods:You only need tof.write(picklejson.dumps(info))Replace pickle.dump(info,f) it with.
It is import
between strings and Python data types.
Pickle, which is used to convert between Python-specific types and Python data types.
JsonImportJsondata= {"K1":"v1","K2":"v2"}#json.dumps () converts data into a string that is known to all programming languages and writes it in a special formWith open ("Test.tx
This article mainly introduced the Python uses the Pickle module realizes "the Adding and deleting" the simple function, has the certain reference value, the interest small partner may consult.
The role of Pickle:
1:pickle.dump (dict,file) converted the dictionary into binary file.
2:pickle.load (file) to convert the binary contents of files into a dictionary
I
JSON Pickle ModulesTwo 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, loadThe
#!/usr/bin/env python#Coding:utf8ImportPickle,jsonImportDatetimedic1= {'name':'Alex', ' Age': 44, 'born':d Atetime.datetime.now ()}#If this is more complex, JSON cannot be parsed, and with pick, you can#memory data is stored, reused, and can be pickle serializedF= File ("D:/TEST.PKL","W") Pickle.dump (dic1,f)#writing data to a filef.close ()#deserializationf = File ("D:/TEST.PKL") Data=pickle.
Python's pickle module implements basic data sequence and deserialization. Through the serialization of the Pickle module we are able to save the object information running in the program to a file, to store it permanently, and through the Pickle module's deserialization, we are able to create from the file the last object saved by the program.
Basic interface:
The
pickle module can serialize objects and save them to disk and read them when needed, and any object can perform serialization operations. In machine learning, we often need to store a well-trained model so that we can make decisions by simply putting the model alone, without having to retrain the model, which saves time.
Pickle Module Common functions
Dump (Obj,file,[,protoco
can improve compatibility3.1 Json.dumps () Import jsondic={'Alex':'+ '# Note the JSON-type string , all in double quotes, at which point the single quote a=json.dumps (DIC)print(a) {"Alex " " - "} # automatically outputs into double quotes, and is compatible with each platformThere is a shortcut, Json.dump (' Sjah ', f)The former is the data that needs to be written, and the latter is the file to be written, which is relatively fast3.2 Json.loads ()Take the JSON type string out, note that i
#!/usr/bin/envpython2 #coding:utf-8 "" "Pickle Role: 1:pickle.dump (Dict,file) Convert the dictionary into a binary file. 2:pickle.load (file) to convert the binary contents of the files into a dictionary . "" importpickle# defadds (): users={"name": "Yangbin", "age":22, "sex": "Male"} withopen ("Red.txt", "WB") asf: pickle.dump (users,f) dic={} withopen ("Red.txt") assd:dic =pickle.load (SD) printdic# here redundancy, purely to highlight the final re
understand, as follows:But this is not an error, not a letter, and finally the load () function to deserialize it after the console output is:Similarly, the loads () function can replace the load function. As follows: 1 print(Pickle.loads (F.read ()))2. JSONPickle is unique to Python, and JSON enables data conversion and transmission in different programming languages. Data transfer in different programming languages requires the conversion of their
Encapsulation is the process of converting a Python data object into a stream of bytes, and unpacking is the inverse of the package, converting bytes in a byte file or byte object into a Python data object, and not unpacking the data from the untrusted data source. Almost any Python data object can be encapsulated and unpacked, mainly including:
None, True,false
JSON serialization and JSON deserialization#!/usr/bin/env Python3#-*-coding:utf-8-*-__author__='life into the play'ImportJsona= { "name":"Test", " Age":" -",}#JSON serializationWith open ("json_test","W", encoding="Utf-8") as F:f.write (Json.dumps (a))#equivalent to this json.dump (a,f)#JSON deserializationWith open ("json_test","R", encoding="Utf-8") as F:Print(Json.loads (F.read ()))#equivalent to this print (Json.load (f))Pickle serialization
It is possible to convert a Python object into a binary form to hold a byte stream called picklingThe process of converting a binary form to an object reads a stream of characters called unpickling>>> Import Pickle >>> my_list =[123,456, ' I love You ', [' another list '] >>> pickle_file = open ('/home/fengjunjie/test/my_list.pkl ', ' WB ') >>> pickle.dump (my_list,pickle_file) >>> pickle_file.close () >>>
Using Python's built-in modules to save, extract data structure objects in Python:
such as lists, dictionaries, collections, and so on.
First import the Pickle module (no installation required):
Import Pickle
To save dictionary data using pickle:
Output_2_3 = open (' P2c_2_3.pkl ', ' WB ')
pickle.dump (P2c_2_3,
This is a two module for serializationJSON: Used to convert between string and Python data typesPickle: Converting between Python-specific types and Python data typesThe JSON module provides four functions: dumps dump loads loadThe Pickle module provides four functions: dumps dump loads loadPickle instances: 1:import
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.