python之xml和shelve模块
一,xml 模块
import xml.etree.ElementTree as ET tree = ET.parse("a.xml") root = tree.getroot() # print(root.tag) # print(root.attrib) # print(root.text) # res=root.iter('year') # 从整个树形结构中寻找 # print(list(res)) # for item in res: # print(item.tag,item.attrib,item.text) # res=root.find('year') # 从当前节点的儿子中查找 # print(res) # res=root.find('country') # 从当前节点的儿子中查找,找成功 一个就结束 # print(res.attrib) # res=root.find('country').find('year') # print(res.text) # res=root.findall('country') # 从当前节点的儿子中查找,找到所有 # print(res) # 遍历 # for country in root: # print('==============>',country.tag,country.attrib) # for item in country: # print(item.tag,item.attrib,item.text) # 改 # for year in root.iter('year'): # print(year.text) # year.text=str(int(year.text) + 1) # print(year.text) # year.attrib={'updated':'yes'} # year.attrib={} # year.attrib.pop('updated') # tree.write('b.xml') # tree.write('a.xml') # 删 # for country in root: # rank=country.find('rank') # v=int(rank.text) # if v > 50: # # print(rank.text) # root.remove(country) # # tree.write('a.xml') # 增 # for country in root: # tag=ET.Element('egon') # tag.attrib={'age':"1",'sex':'male'} # tag.text='老男孩的最帅的老师' # country.append(tag) # tree.write('a.xml') for country in root: tag=country.find('egon') print(tag.text)
二,shelve 模块
import shelve # userinfo={ # 'egon':{'age':18,'sex':'male'}, # 'alex':{'age':38,'sex':'female'}, # } f=shelve.open(r'sheve.txt',writeback=True) # f['egon']={'age':18,'sex':'male'} # f['alex']={'age':38,'sex':'female'} # f['egon']['age']=19 print(f['egon']['age']) f.close()
优质内容筛选与推荐>>