Python serialization Module

Source: Internet
Author: User

 #什么叫序列化模块: # # The process of converting an original dictionary, list, and so on into a string is called Serialization # #序列化的目的: # #1. To persist a custom object in some form of storage # #2. Pass the object from one place to another # #3. Make the program more maintainability. # # Str>>>> Deserialization >>>> Data Structure # # Data Structure >>>> serialization >>>>>>> str## # json# # JSON module offers four features: Dumps dump loads load# import json# # dumps and loads# dic = {"K1": "V1", "K2": "V2", "K3 ":" v3 "}# str_dic = Json.dumps (DIC) # Serialization: Converting a Dictionary to a string # print (Type (str_dic), str_dic) # <class ' str ' > {" K1 ":" V1 "," K2 ":" V2 "," K3 ":" V3 "}# # Note: The string in the dictionary of the string type converted by JSON is represented by" "(Double Punctuation) # # Dic2 = Json.loads (str_dic) # deserialization: Converts a dictionary of a string format into a A dictionary # print (type (DIC2), dic2) # <class ' dict ' > {' K1 ': ' v1 ', ' K2 ': ' v2 ', ' K3 ': ' V3 '}# #注意: A Dictionary of String types processed with the loads function of JSON The string must be represented by "" # # list_dic = [1,[' A ', ' B ', ' C '],3,{' K1 ': ' v1 ', ' K2 ': ' v2 '}]# str_dic = Json.dumps (list_dic) # can handle nested data types # Print (Type (str_dic), str_dic) # <class ' str ' > [1, ["A", "B", "C"], 3, {"K1": "V1", "K2": "v2"}]# List_dic2 = json.load S (str_dic) # Print (Type (lIST_DIC2), List_dic2) # <class ' list ' > [1, [' A ', ' B ', ' C '], 3, {' K1 ': ' v1 ', ' K2 ': ' v2 '}]### # dump and load## f = open ( ' Json_file ', ' W ') # dic4 = {' K1 ': ' v1 ', ' K2 ': ' v2 ', ' K3 ': ' V3 '}# json.dump (dic4,f) # The Dump method receives a file handle and writes the dictionary directly to the Hson string after writing to the file # F.close () # Close File # # f = open (' Json_file ') # dic5 = Json.load (f) # The Load method receives a file handle that directly converts a string in the file into a data structure return # f.close () # print (t Ype (DIC5), dic5) # <class ' list ' > [1, [' A ', ' B ', ' C '], 3, {' K1 ': ' v1 ', ' K2 ': ' V2 '}] #import json# dumps and dump in ENS ure_ascii keyword # f = open (' File ', ' W ', encoding= "Utf-8") # Json.dump ({' Nationality ': ' China '},f) # ret = Json.dumps ({' International ': ' China '}) # F.write ( Ret+ "\ n") # After writing inside is the bytecode # f.close () # # Json.dump ({' Nationality ': ' China '},f,ensure_ascii=false) # Ret1 = Json.dumps ({' Nationality ': ' China '},ensure _ascii=false) # f.write (ret1+ "\ n") # write to show Chinese # f.close () #json的格式化输出 # import json# data = {' username ': [' Li Hua ', ' Erlengzi '], ' sex ' : ' Male ', ' age ': 16}# Json_dic2 = Json.dumps (data,sort_keys=true,indent=2,separators= (', ', ': '), Ensure_ascii=false) # Print (JSON_DIC2) # for users to see, save the file wasted memory # Result: #{# "Age": 16,# "Sex": "Male", # "username": [# "Li Hua", # "Erlengzi" #]#} #json用法写的一些注意事项 #import json#json format Restrictions 1,json format Key must be a string data type #json format string can only be "" (double quotation marks) #如果是数字为key, then the dump will be forcibly transferred to the string data type # dic = {1:2,3:4}# str_dic = Json.dumps (DIC) # Print (Type (str_dic), str_dic) # <class ' str ' > {"1": 2, "3": 4}# New_dic = Json.loads (str_dic) # Print (Type (new_dic), n Ew_dic) # <class ' dict ' > {' 1 ': 2, ' 3 ': 4}# JSON supports tuples, dictionaries that do value for tuples will cast tuples into List # dic = {' abc ':(-and------)}# str_dic = JS On.dumps (DIC) # Print (Type (str_dic), str_dic) # <class ' str ' > {"abc": [1, 2, 3]} go to list # new_dic = Json.loads (str_dic) # print (new_dic) # {' abc ': [1, 2, 3]} convert back to value or list #json support tuple do key, do not support # dic = {(One-way): ' abc '}# str_dic = Json.dumps (di c) # Error key must be str, int, float, bool or none, not tuple# to list dump# lst = ["AAA", 123, ' BBB ', 4.66]# with open (' Json_demo ', ' W ') as F : # Json.dump (lst,f) # with open (' Json_demo ') as f:# ret = Json.load (f) # print (ret) # [' AAA ', 123, ' BBB ', 4.66] # #能不能多次dump数据到文件里, can dump into a file multiple times but notCan load out # dic = {' abc ':(}#) lst = ["AVC", 123,44,34]# with open (' Json_demo ', ' W ') as f:# json.dump (lst,f) # JSON. Dump (dic,f) # Multiple dump to file # with open (' Json_demo ') as f:# ret = Json.load (f) # error # print (ret) # #想dump多个数据进入文件, with Dum  ps# dic = {' abc ':()}# lst = [' abc ', 123]# with open (' Json_demo ', ' W ') as f:# str_lst = Json.dumps (LST) # Str_dic = Json.dumps (DIC) # f.write (str_lst+ "\ n") # f.write (str_dic+ "\ n") # # with open (' Json_demo ') as f:# for line in F : # ret = Json.loads (line) # print (ret) # All Out # results: #[' abc ', 123] #{' abc ': [1, 2, 3]}# Chinese format Ensure_ascii = false# dic = {' AC ':(1,23,3), "Country": "China"}# ret = Json.dumps (dic,ensure_ascii=false) # print (ret) # {"AC": [  1, 23, 3], "Country": "China"}## dic_new = Json.loads (ret) # print (dic_new) # {' AC ': [1, 23, 3], ' Country ': ' China '}# set set cannot be dump and dumps# Pickle module four functions: Dumps,dump (serialization, Save), loads (deserialization, read), load# Pickle can serialize any data type in Python #dump the result is bytes,dump with the F file handle need to ' WB ' In the form of open, load f is ' RB ' mode read # Almost all data classes supportedSerialization # for object serialization requires the class of this object object in memory # for multiple dump\load operations done well #import pickle# dic = {1: (All-in-one), (' A ', ' B '): 4}# pic_dic = Pickle.dumps (DIC) # Print (Type (pic_dic), pic_dic) # <class ' bytes ' > B ' \x80\x03}q\x00 (k\x01k\ bytse Type # # new_dic = P Ickle.loads (pic_dic) # print (new_dic) # {1: (1, 2, 3), (' A ', ' B '): 4} #pickle支持几乎所有对象的 # class student:# def __init__ ( self,name,age): # self.name = name# Self.age = age# Alex = Student ("Alex", "Max") # ret = Pickle.dumps (Alex) # PR int (ret) # byte # # Pic_ret = Pickle.loads (ret) # print (Pic_ret) # <__main__. Student object at 0x0000000002696eb8># print (pic_ret.name) #alex # Print (pic_ret.age) # 40import pickle# class S tudent:# def __init__ (self,name,age): # self.name = name# Self.age = age# Alex = Student ("Alex", page) # WI      Th open (' Pickle_demo ', ' WB ') as f:# pickle.dump (alex,f) # with open (' Pickle_demo ', "RB") as f:# ret = Pickle.load (f) # Print (ret) # <__main__. Student object at 0x00000000028a6358># PRint (ret.name) # # with open (' Pickle_demo ', ' WB ') as f:# pickle.dump ({' K1 ': ' v1 '},f) # pickle.dump ({' K2 ': ' V2 '},f) # # with         Open (' Pickle_demo ', ' RB ') as F: # cannot be used for loop, do not know how many files # while 1:# try:# print (Pickle.load (f)) # Except Eoferror: # exception Capture # break# result # {' K1 ': ' v1 '}# {' K2 ': ' v2 '} #shelve the serialization tool has only one open method import Shelvef = s Helve.open (' Shelve_demo ') f[' key ') = {' K1 ':(), ' K2 ': ' V2 '}f.close () F = shelve.open (' shelve_demo ') content = f[' key ' ]f.close () print (content) # {' K1 ': (1, 2, 3), ' K2 ': ' v2 '} #shelve if a file is written, the change is less, the read is more, and most of the reads are # based on a key to obtain a value

  

Python serialization Module

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.