python之shelve模块、xml模块

shevle模块比pickle模块简单,只要一个open模式,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型

如下例题:

import shelve

# dic1={'pwd':'alex3714','age':18,'sex':'male'}
# dic2={'pwd':'alex3715','age':73,'sex':'male'}

d=shelve.open('db.txt',writeback=True)
d['egon']=dic1
d['alex']=dic2
 d['egon']['age']=19
print(d['egon'])

d.close()

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,单json使用起来更简单

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>


 

xml数据

import xml.etree.ElementTree as ET

tree = ET.parse("a.xml")          #解析文件

root = tree.getroot()  #树形结构,拿到树根

对于任何标签都有三个特征:标签名、标签属性、标签的文本内容

# print(root.tag) #标签
# print(root.attrib) #标签属性

# print(root.text) #标签的文本内容

全文搜索,找到所有
# for year in root.iter('year'):
#     print(year.tag)
#     print(year.attrib)
#     print(year.text)

#     print('='*100)

# print(root.find('country').attrib)     #在root的子节点找,只找一个

# print([country.attrib for country in root.findall('country')]) #在root的子节点找,找所有

1、查
#遍历整个文档
# for country in root:
#     print('============>国家 %s' %country.attrib)
#     for item in country:
#         print(item.tag)
#         print(item.attrib)
#         print(item.text)


2、改
# for year in root.iter('year'):
#     print(year.tag)
#     year.attrib={'updated':'yes'}
#     year.text=str(int(year.text)+1)
#
# tree.write('a.xml')


3、增
# for country in root:
#     rank=country.find('rank')
#     if int(rank.text) > 50:
#         # print('符号条的国家',country.attrib)
#         tag=ET.Element('egon')
#         tag.attrib={'updated':'yes'}
#         tag.text='NB'
#         country.append(tag)
#

# tree.write('a.xml')

4、删

for country in root:
    tag=country.find('egon')
    # print(tag,bool(tag))
    if tag is not None:
        print('====>')
        country.remove(tag)
tree.write('a.xml')

原文地址:https://www.cnblogs.com/Marcki/p/10111949.html