python序列化之json
import json dic={'name':'one','age':'18'} json.dumps(dic) # 类型变成了json字符串类型 print(type(json.dumps(dic))) # 要是想永久保存,就写到文件中 # 第一种 # 写 with open('a.json','w') as f: f.write(json.dumps(dic)) # 读 with open('a.json','r') as f: data=f.read() # 转化为字典类型 dic=json.loads(data) print(dic['name']) # 第二种 dic={'name':'one','age':'18'} # 写 json.dump(dic,open('b.json','w')) # 读 json.load(open('b.json','r')) print(json.load(open('b.json','r'))['name'])
eval和json的区别:
eval是将字符串中的命令提取出来,执行一遍
json是把一个数据类型按照json类型转成json认识的字符串,即json序列化。json反序列化就是将json类型转化为原来的类型
shelve存取数据
import shelve # 存数据 f=shelve.open(r'shelve.sh') f['one']={'age':18,'pwd':'123'} f['two']={'age':28,'pwd':'456'} # 别忘了close掉 f.close()
import shelve # 取数据 f=shelve.open(r'shelve.sh') res=f['one'] f.close() print(res)
xml模块:
import xml.etree.ElementTree as ET tree=ET.parse('a.xml') root=tree.getroot() for child in root: print('===>',child) for i in child: # 打印标签,属性,内容 print(i.tag,i.attrib,i.text)
查找element元素的三种方式:
import xml.etree.ElementTree as ET tree=ET.parse('a.xml') root=tree.getroot() # 查找element元素的三种方式 # 第一种: years=root.iter('year')#扫描整个xml文档树 for i in years: print(i) # 第二种: res1=root.find('country')#谁来调,就从谁的下一层中找第一个 print(res1) # 第三种: res2=root.findall('country')#谁来调,就从谁的下一层中找所有 print(res2)