python configparse模块&xml模块

configparse模块

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[bitbucket.org]
user = hg

[topsecret.server.com]
port = 50022
forwardx11 = no

[group]
import configparser
# ------------------------------------读----------------------------------
# 读取文件内容
config = configparser.ConfigParser()                  # 实例化(生成对象)
config.read("config_file.cnf", encoding="utf-8")  # 读取配置文件
ret = config.sections()                              # 调用sections方法(默认不会读取default)
print(ret)
print("bitbucket.org" in config)                  # 判断元素是否在sections列表内
print(config["bitbucket.org"]["user"])             # 通过字典的形式取值
for i in config["topsecret.server.com"]:          # for 循环"topsecret.server.com"字典中key
    print(i)
for i,v in config["topsecret.server.com"].items():  # 使用items函数循环"topsecret.server.com"字典的键和值
    print(i,v)
# 还有另一种读法
options = config.options("bitbucket.org")         # 获取指定section的keys,(default 下的key默认读取)
print(options)
item_li = config.items("bitbucket.org")           # 使用items获取指定section的键和值,元祖的形式,(default 下的key默认读取)
print(item_li)
val = config.get("bitbucket.org", "user")        # 使用get获取指定键的值
print(val)

# -------------------------改----------------------------
# config.add_section("group")                 # 新增一个sections,指定的section已存在时,报错
#has = config.has_section("group",name)       # 检查
# print(has)
# config.set("group", "name", "sb")               # 修改指定的section下的指定的键的值,若键不存在,自动添加
# config.add_section("group1")
config.remove_section("group1")                 # 删除指定的sections ,sections不存在不会报错
config.remove_option("group","name")            # 删除指定的sections下指定的键值对
config.write(open("config_file.cnf", "w"))    # 修改后写入文件生效

xml模块

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。

<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year update="yes">2016</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria" />
        <neighbor direction="W" name="Switzerland" />
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year update="yes">2019</year>
        <gdppc>59900</gdppc>
        <neighbor direction="N" name="Malaysia" />
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year update="yes">2019</year>
        <gdppc>13600</gdppc>
        <neighbor direction="W" name="Costa Rica" />
        <neighbor direction="E" name="Colombia" />
    </country>
</data>
# xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml
import xml.etree.ElementTree as ET
tree = ET.parse("xml_file.xml")
root = tree.getroot()
print(root.tag)
# 遍历xml文档
for xx in root:
    print(xx.tag, xx.attrib)
    for i in xx:
        print(i.tag,i.text)
        
# 只遍历年
for i in root.iter("year"):
    print(i.tag,i.text)
# 修改
for i in root.iter("year"):
    new_year = int(i.text) + 1
    i.text = str(new_year)
    i.set("update","yes")
tree.write("xml_file.xml")
# 删除
for country in root.findall("country"):
    rank = int(country.find("rank").text)
    if rank >= 50:
        root.remove(country)
tree.write("out_file.xml")

创建一个xml文件

# 创建一个xml
new_xml = ET.Element("name_list")
name = ET.SubElement(new_xml, "name",attrib={"enrolled":"yes"})
age = ET.SubElement(name,"age",attrib={"cheked": "no"})
sex = ET.SubElement(name,"sex")
sex.text = "33"
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled": "no"})
age = ET.SubElement(name2,"age")
age.text = "19"
et = ET.ElementTree(new_xml)
et.write("test.xml",encoding="utf-8",xml_declaration=True)
ET.dump(new_xml)
<?xml version='1.0' encoding='utf-8'?>
<name_list><name enrolled="yes"><age cheked="no" /><sex>33</sex></name><name enrolled="no"><age>19</age></name></name_list>
原文地址:https://www.cnblogs.com/zt0903/p/10687041.html