• xml和configparser模块


    一、xml模块

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

     但至今很多传统公司如金融行业的很多系统的接口还主要是xml。

      xml的格式如下,就是通过<>节点来区别数据结构的:

    <?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协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml 

    # _*_coding:utf-8_*_
    
    import xml.etree.ElementTree as ET
    # xml 通过<> 节点区别数据结构
    
    tree = ET.parse("xml test") # open 文件
    root = tree.getroot() #f.seek(0)
    #print(dir(root))
    print(root.tag) # 打印标签
    #
    #遍历xml文档
    for child in root:
        print('----------',child.tag, child.attrib)
        for i in child:
            print(i.tag,i.text)
    
    #只遍历year 节点
    for node in root.iter('year'):
        print(node.tag,node.text)

      修改和删除xml文档内容

    # _*_coding:utf-8_*_
    
    import xml.etree.ElementTree as ET
    
    tree = ET.parse("xml test")
    root = tree.getroot() #f.seek(0)
    
    #修改
    for node in root.iter('year'):
        new_year = int(node.text) - 1
        node.text = str(new_year) # 必须是字符串
        node.set("revise_test","yes")
    
    #删除node
    for country in root.findall('country'):
       rank = int(country.find('rank').text)
       if rank > 50:
         root.remove(country)
    
    tree.write('output.xml')

      自己创建xml文档

    import xml.etree.ElementTree as ET
    
    
    new_xml = ET.Element("namelist")
    name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
    age = ET.SubElement(name,"age",attrib={"checked":"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) #打印生成的格式

    二、configparser模块

      configparser模块用于生成和修改常见配置文档。

      常见配置文件格式如下:

    [DEFAULT]
    ServerAliveInterval = 45
    Compression = yes
    CompressionLevel = 9
    ForwardX11 = yes
    
    [bitbucket.org]
    User = hg
    
    [topsecret.server.com]
    Port = 50022
    ForwardX11 = no

      解析配置文件

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    
    import configparser
    
    conf = configparser.ConfigParser()
    #print(conf.sections())
    conf.read('conf.ini')
    print(conf.sections())
    print(conf.default_section) # DEFAULT
    print(conf['bitbucket.org']['user']) # hg
    
    print(list(conf['bitbucket.org'].keys())) #
    # ['user', 'maxusers', 'compression', 'compressionlevel', 'serveraliveinterval', 'forwardx11']
    
    for k,v in conf['bitbucket.org'].items():
        print(k,v)
    '''
    user hg
    maxusers 100
    compression yes
    compressionlevel 9
    serveraliveinterval 45
    forwardx11 yes
    '''
    # default 中的参数是默认每个里面都有的
    
    if 'user' in conf['bitbucket.org']:
        print('it is right')

      增删改查语法

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    
    import configparser
    conf = configparser.ConfigParser()
    
    conf.read('conf_test.ini')
    print(dir(conf))
    
    #
    print(conf.options('group1'))     # ['k1', 'k2']
    print(conf['group1']['k1'])        # v1
    print(conf.get('group1','k1'))    # v1
    
    # 增加
    conf.add_section('group3')     # 添加节点
    conf['group3']['name'] = 'cc'
    conf['group3']['age'] = '21   ' # 必须为字符串
    conf.write(open('conf_test_new.ini','w'))
    
    #
    conf.set('group2','k1','666666')
    conf.write(open('conf_test_new.ini','w'))
    
    #
    conf.remove_option('group1','k2')
    conf.remove_section('group2')
    conf.write(open('conf_test_new.ini','w'))

       文章摘录整理自https://www.luffycity.com/python-book/di-4-zhang-python-ji-chu-2014-chang-yong-mo-kuai/configparser-mo-kuai.html

  • 相关阅读:
    NetBeans Visual Library Tutorial
    Introduction to the PeertoPeer Sockets Project
    p2psockets代码
    摄像头说明
    Best practice to use ConcurrentMap's putIfAbsent
    转:jxmultisplitpane: how to use?
    格式化文本支持:JTextPane
    中国维护的对象标识符定义
    对称加密DES和TripleDES
    Kerberos的原理 MIT
  • 原文地址:https://www.cnblogs.com/schut/p/8437192.html
Copyright © 2020-2023  润新知