json模块:
json:与任何语言之间都可以进行信息交换(字符串的转换)
经过json转换,所有类型均可先转换为双引号形式 再转换为str
例如:文件的读写:
1 #写文件: 2 import json 3 f = open("demo.txt","w") 4 dic = {"name":"g_l"} 5 dic_str = json.dumps(dic) 6 f.write(dic_str) 7 print(type(dic_str)) 8 print(dic_str)
1 #读文件: 2 import json 3 f = open("demo.txt","r") 4 f_read = f.read() 5 f_read = json.loads(f_read) 6 print(type(f_read)) 7 print(type(f_read))
仅仅针对文件操作的 load和dump:【dic f 参考上面两个代码】
json.dump(dic,f)
json.load(f)
packle模块:(支持函数、类等)
序列化:把变量(对象)从内存中变成可存储或者传输的过程称为序列化
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import pickle 2 dic = {"name":"alex","name":"g_l","age":18} 3 # print(type(dic)) 4 j = pickle.dumps(dic) 5 print(type(j))#字节类型 6 print(j) 7 f = open("序列化对象_pickle",'wb') 8 pickle.dump(dic,f)#f.write()#不可读文件 9 f.close() 10 # #---反序列化: 11 import pickle 12 f = open("序列化对象_pickle",'rb') 13 date = pickle.loads(f.read())#---->date = pickle.load(f) 14 print(type(date["age"])) 15 print(date["age"])
shelve模块:
相对于pickle模块更简单,只有一个open函数;
返回类似于字典的对象;
可读可写;
key必须为字符串;
value是python可支持的所有类型
xml模块:
i.tag--->属性
i.attrib--->键值对(属性)
i.text--->标签下的内容
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import xml.etree.ElementTree as ET 2 tree = ET.parse("xml_lesson") 3 root = tree.getroot() 4 print(root) 5 print(root.tag) 6 for i in root: 7 print(i) 8 print(i.tag) 9 print(i.attrib) 10 for sx in i: 11 print(i) 12 print(sx.tag)#打印属性 13 print(sx.attrib) 14 print(sx.text) 15 # #遍历节点: 16 for node in root.iter('year'): 17 print(node.tag,node.text) 18 19 #修改信息: 20 for node in root.iter('year'): 21 new_year = int(node.text)+1 22 node.text=str(new_year) 23 node.set("updata","yes") 24 tree.write('xml_xg.xml') 25 26 #删除信息: 27 for country in root.findall('country'): 28 gdp=int(country.find('gdp').text) 29 if gdp<5000: 30 root.remove(country) 31 tree.write('xml_xg.xml') 32 33 #xml数据的创建: 34 import xml.etree.ElementTree as XET 35 new_xml = ET.Element("namelist")#根节点 36 """ 37 创建 <namelist> 38 </namelist>标签 39 """ 40 name = XET.SubElement(new_xml,"name",attrib={"enrolled":"yes"}) 41 age = XET.SubElement(name,"age",attrib={"checked":"no"}) 42 sex = XET.SubElement(name,"sex") 43 """ 44 <namelist> 45 <name enrolled="yes"></name> 46 <age checked="no"></age> 47 <sex></sex> 48 </namelist> 49 """ 50 sex.text='18' 51 name2 = XET.SubElement(new_xml,"name",attrib={"enrolled":"no"}) 52 age = XET.SubElement(name2,"age") 53 age.text = '8' 54 55 et = ET.ElementTree(new_xml)#生成文档对象 56 et.write("test.xml",encoding="utf-8",xml_declaration=True) 57 58 XET.dump(new_xml)#打印生成的格式