1、json & pickle 模块
用于序列化的两个模块, 通过将对象序列化可以将其存储在变量或者文件中,可以保存当时对象的状态,实现其生命周期的延长。并且需要时可以再次将这个对象读取出来。
序列化:在python中,序列化可以理解为:把python的对象编码转换为json格式的字符串,反序列化可以理解为:把json格式字符串解码为python数据对象。
-
json,用于字符串 和 python数据类型间进行转换
-
pickle,用于python特有的类型 和 python的数据类型间进行转换
Json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load
Json 和 pickle 区别:
1、json是可以在不同语言之间交换数据的,而pickle只在python之间使用。
2、json只能序列化最基本的数据类型,而pickle可以序列化所有的数据类型,包括类,函数都可以序列化。
1 #序列化1 2 import json 3 info1 = { 4 "name" : "boss1", 5 "age" : "1" 6 } 7 f = open("序列化文件","w",encoding="UTF-8") 8 f.write(json.dumps(info1)) 9 # json.dump(info1,f) #简便写法
10 #-----------------------------------------------------------------------------------
11 #反序列化1 12 import json 13 14 f = open("序列化文件","r") 15 data = json.loads(f.read()) 16 # data = json.load(f) #简便写法 #反序列化步骤1、先读取文件的字符串对象2、然后反序列化成列表对象 17 print(data) 18 print(data["name"])
#序列化2 字典里加上方法
2 import pickle 3 def sayhi(name): 4 print("%s,hello"%name) 5 info2 = { 6 "name" : "big", 7 "age" : "25", 8 "fun" : sayhi 9 } 10 f = open("序列化文件2","wb") 11 f.write(pickle.dumps(info2)) 12 # pickle.dump(info2,f) #简便写法
13 #----------------------------------------------------------------------------------
14 #反序列化2 15 import pickle 16 f = open("序列化文件2","rb") 17 #所以需要写上数据里的函数,才可以成功调用 18 def sayhi(name): 19 print("%s,hello"%name) 20 data = pickle.loads(f.read()) #运行次行,如果没有写入函数sayhi,会报错 ,因为在序列化完毕后,文件关闭,在此开启则找不到内存地址了 21 # data = pickle.load(f) #简便写法 22 print(data) 23 print(data["fun"]("dage"))
24 #打印结果: 25 # {'name': 'big', 'age': '25', 'fun': <function sayhi at 0x0073EA08>} 26 # dage,hello 27 # None
2、shelve模块
shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型
1 import shelve 2 3 f=shelve.open(r'sheve.txt') 4 # f['stu1_info']={'name':'egon','age':18,'hobby':['piao','smoking','drinking']} 5 # f['stu2_info']={'name':'gangdan','age':53} 6 # f['school_info']={'website':'http://www.pypy.org','city':'beijing'} 7 8 print(f['stu1_info']['hobby']) 9 f.close()
3、xml模块
xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。
xml的格式如下,就是通过<>节点来区别数据结构的:
1 <?xml version="1.0"?> 2 <data> 3 <country name="Liechtenstein"> 4 <rank updated="yes">2</rank> 5 <year>2008</year> 6 <gdppc>141100</gdppc> 7 <neighbor name="Austria" direction="E"/> 8 <neighbor name="Switzerland" direction="W"/> 9 </country> 10 <country name="Singapore"> 11 <rank updated="yes">5</rank> 12 <year>2011</year> 13 <gdppc>59900</gdppc> 14 <neighbor name="Malaysia" direction="N"/> 15 </country> 16 <country name="Panama"> 17 <rank updated="yes">69</rank> 18 <year>2011</year> 19 <gdppc>13600</gdppc> 20 <neighbor name="Costa Rica" direction="W"/> 21 <neighbor name="Colombia" direction="E"/> 22 </country> 23 </data> 24 25 xml数据
xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml:
# print(root.iter('year')) #全文搜索 # print(root.find('country')) #在root的子节点找,只找一个 # print(root.findall('country')) #在root的子节点找,找所有
1 import xml.etree.ElementTree as ET 2 3 tree = ET.parse("xmltest.xml") 4 root = tree.getroot() 5 print(root.tag) 6 7 #遍历xml文档 8 for child in root: 9 print('========>',child.tag,child.attrib,child.attrib['name']) 10 for i in child: 11 print(i.tag,i.attrib,i.text) 12 13 #只遍历year 节点 14 for node in root.iter('year'): 15 print(node.tag,node.text) 16 #--------------------------------------- 17 18 import xml.etree.ElementTree as ET 19 20 tree = ET.parse("xmltest.xml") 21 root = tree.getroot() 22 23 #修改 24 for node in root.iter('year'): 25 new_year=int(node.text)+1 26 node.text=str(new_year) 27 node.set('updated','yes') 28 node.set('version','1.0') 29 tree.write('test.xml') 30 31 32 #删除node 33 for country in root.findall('country'): 34 rank = int(country.find('rank').text) 35 if rank > 50: 36 root.remove(country) 37 38 tree.write('output.xml')
1 #在country内添加(append)节点year2 2 import xml.etree.ElementTree as ET 3 tree = ET.parse("a.xml") 4 root=tree.getroot() 5 for country in root.findall('country'): 6 for year in country.findall('year'): 7 if int(year.text) > 2000: 8 year2=ET.Element('year2') 9 year2.text='新年' 10 year2.attrib={'update':'yes'} 11 country.append(year2) #往country节点下添加子节点 12 13 tree.write('a.xml.swap')
自己创建xml文档:
1 import xml.etree.ElementTree as ET 2 3 4 new_xml = ET.Element("namelist") 5 name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"}) 6 age = ET.SubElement(name,"age",attrib={"checked":"no"}) 7 sex = ET.SubElement(name,"sex") 8 sex.text = '33' 9 name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"}) 10 age = ET.SubElement(name2,"age") 11 age.text = '19' 12 13 et = ET.ElementTree(new_xml) #生成文档对象 14 et.write("test.xml", encoding="utf-8",xml_declaration=True) 15 16 ET.dump(new_xml) #打印生成的格式