,sort_keys=true,indent=10,separators= (', ', ': '), Ensure_ascii=false)Print(JSON_DIC2)Liu, PickleTwo module JSON for serialization, for converting between string and Python data typesPickle for conversion between Python-specific types and Python data typesThe Pickle module provides four functions: dumps, dump (serialization, Save), Loads (deserialization, read), load (can not only se
Serialization:Serialization refers to converting the data type in memory into a string so that it can be stored on the hard disk or transmitted over the network to the remote, because the hard disk or the network can only accept bytes when it is transmitted.Deserialization:Convert the character into an in-memory data type.Two modules for serialization. They are used exactly the same way.
JSON, used to convert between string and Python data ty
;G T F.close () >>> f = open (' Test.txt ', ' RB ') >>> Pickle.load (f) {' age ': +, ' name ': ' BOB ', ' degree ': ' Master '} >>> Work2 = Pickle.load (f) >>> Work2 (All-in-all) >>> pickle.load (f) EOF Error:ran out of inputJSON moduleSimilar to the Pickle module, but the stored data type is not binary based, but the data format used for text pickle is Python-specific, and
loads function, strings in a dictionary of type string must be represented by ""‘‘‘```Ps:json can be used for data exchange between different languagesPickle is dedicated in Python and can be serialized on any data type, resulting in bytes type * * *Shelve only provides an open method that operates a bit like a dictionary. * * *# # Pickle:four_leaf_clover:Convert between Python-specific types and Python data typesThe Pickle module also offers four me
Before I learned to use the eval built-in method to turn a string into a Python object, the Eval method is limited and can be used for normal data types, json.loads and eval, but when you encounter a special type, eval doesn't work. So the focus of eval is usually to execute a string expression and return the value of the expression.Import Jsonx="[null,true,false,1]"print(eval (x))print( Json.loads (x))What is serialization?The process of changing an object (variable) from memory to a storage or
recognized single quotes #dct=str ({"1 ":111}) #报错 because the generated data is still single quotes: {'one'1}DCT ='{' 1 ': ' 111 '}'print (Json.loads (DCT)) #conclusion: # No matter how the data is created, As long as the JSON format is satisfied, it can be json.loads out, not necessarily dumps data to loadsPickleImport Pickle dic={'name':'Alvin',' Age': at,'Sex':'male'} print (Type (DIC)) #class
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, loadThe Pickle module provides four functions: d
Serialization modules: JSON and PickleTwo 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
JSON Pickle Modules
JSON modules: Only for simple data types, is a cross-platform module.Let's say we have a piece of data that defines this:= { ‘name‘:‘alex‘, ‘age‘:22}For this simple data type, we can directly use theJsonFor serialization and deserialization of data:
Serialization dumps :import=open("test.text","wb")f.write(json.dumps(
JSON and PickleJSON and pickle are used for string serialization and deserialization, and when we store and use it, we often save the list in a file, and we want to read it as a list when we read it. You need to use JSON and pickle. JSON is a support for all interfaces, and
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
SceneExample 1dic=Str ({' Age':' -'})f= Open ('text','W') F.write (DIC) F.close () Example 2f= Open ('text','R') Data=F.read ()Print(Eval (Data) [' Age'])When we store the memory data object in a file, it is impossible to store the Dictionary object directly, it must be converted to the string format str (), when we read the dictionary format object stored in the file through the F.read () method, the reading is also a string that must be converted with the Eval () method, which is very Lou.Two
bar (), but now have to change to use_logging (bar). So is there a better way? Of course, the answer is an adorner.1. Non-parametric adornerImport TimedefTimer (func):defdeco (): Start_time=time.time () func () Stop_time=time.time ()Print("The func run time is%s"% (stop_time-start_time)) returnDeco@timer#equivalent to Time1=timer (time1)deftime1 (): Time.sleep (1) Print(" in the time") time1 ()" "In the timethe func run time is 1.0000569820404053" "2. Parametric decoratorImport TimedefTimer
': ' Engine ' }}}Second, pickle serialization module#! /usr/bin/env Python3#-*-coding:utf-8-*-#Write by CongcongImportpickledict= {'name':'cc',' Age': 21}len= ['python','Hello',' World']#Dumps D = Pickle.dumps (dict)#string converted to bytes typePrint(d)#B ' \x80\x03}q\x00 (x\x04\x00\x00\x00nameq\x01x\x02\x00\x00\x00ccq\x02x\x03\x00\x00\x00ageq\x03k\x15u. ' )D_1 = Pickle.loads (d)#bytes Type to original data type#print (d_1) # {' Name ': ' CC ', ' A
and deserializes a serialized string from a fileWith open ("Test1.txt","RB") as F:Print(Pickle.load (f))#The result is: {' K1 ': ' v1 ', ' K2 ': ' V2 '}#pickle.dumps () converts data into a string that is recognized by all programming languages in a special formPICKLE_STR1 =pickle.dumps (data)Print(PICKLE_STR1)#The result is: B ' \x80\x03}q\x00 (x\x02\x00\x00\x00k1q\x01x\x02\x00\x00\x00v1q\x02x\x02\x00\x00\x00k2q\x03x\x02\x00\x00 \x00v2q\x04u. '#Pickle.loads deserializing a serialized stringPIC
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
JSON PickleJSON: Typically used for serialization and deserialization between different programming languages, the core of which is the string, which is the conversion between the string and the basic data type of PythonThe JSON module provides four functions:dumps, dump(serialization, Save), loads(deserialization, read), load #json.loads is used to convert strings in dictionaries, lists, and elements into
", 5 "name": "Jack", 6 "country": "China" 7 } 8 with Ope N ("Demo.txt", "W") as F:9 date=json.dump (dic,f) #json_反序列化2. PY14 Import json15 with open ("Demo.txt", " R ") as F:16 dic1=json.load (f)-Print (dic1[" name "])
As you can see, dump () and load () are the encapsulation of dumps () and loads () and the read and write operations of the file.
Pickle
Pickle also has the above fou
number 8 o'clock exits the programSys.exit ()Import Syscount = 1while count Output Result:12345678View Code(3) Sys.version methodDefinition: Get version information for the Pyhon interpreter(4) Sys.maxint methodDefinition: the largest int value(5) Sys.path methodDefinition: Returns the search path of the module, initializing the value using the PYTHONPATH environment variableExample 1:Import Sysprint (Sys.path) # Get the search path for the moduleOutput Result:['C:\\users\\william\\pycharmproje
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.