python内置模块(三)

----------------------------接 python内置模块(二)---------------------------

八、 shelve模块

     shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式他只有一个函数就是open(),这个函数接收一个参数就是文件名,然后返回一个shelf

对象,你可以用他来存储东西,就可以简单的把他当作一个字典,当你存储完毕的时候,就调用close

函数来关闭。

                >>> import shelve

        >>> sfile = shelve.open('shelve_test')    # 打开一个文件

        >>> sfile['k1'] = []               # 持久化存储列表

        >>> sfile['k1']

        []

        >>> sfile.close()                  # 文件关闭

九、 xml处理模块

xml是实现不同语言或程序之间进行数据交换的协议,xml通过<>节点来区别数据结构的:

<?xml version="1.0"?>

< data >
     < 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("test.xml")

        root = tree.getroot()

        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文档

        import xml.etree.ElementTree as ET

        tree = ET.parse("test.xml")

        for node in root.iter('year'):

            new_year = int(node.text) + 1

            node.text = str(new_year)

            node.set("updated","yes")

        

        tree.write("test.xml")

        for node in root.iter('year'):

            print(node.tag,node.text)

删除xml内容

        #删除node

        import xml.etree.ElementTree as ET

        tree = ET.parse("test.xml")

        for country in root.findall('country'):

           rank = int(country.find('rank').text)

           if rank > 50:

             root.remove(country)

        

        tree.write('test.xml')

        for child in root:

            print(child.tag, child.attrib)

            for i in child:

                print(i.tag,i.text)

创建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")

        age.text = '33'

        sex.text = 'F'

        name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})

        age = ET.SubElement(name2,"age")

        sex = ET.SubElement(name2,"sex")

        age.text = '19'

        sex.text = 'M'

        

        et = ET.ElementTree(new_xml) #生成文档对象

        et.write("test.xml", encoding="utf-8",xml_declaration=True)

        

        ET.dump(new_xml) #打印生成的格式


        <namelist>
            <name enrolled="yes">
                <age checked="no">33</age>
                <sex>F</sex>
            </name>
            <name enrolled="no">
                <age>19</age>
                <sex>M</sex>
            </name>
        </namelist>

十、 ConfigParser模块

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

            常见软件配置文档格式如下:

         [DEFAULT]

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

生成配置文件方法:

       import configparser

        config = configparser.ConfigParser()

        

        config["DEFAULT"] = {}

        config["DEFAULT"]['ServerAliveInterval']=  '45'

        config["DEFAULT"]['Compression'] = 'yes'

        config["DEFAULT"]['CompressionLevel'] = '9'

        config['DEFAULT']['ForwardX11'] = 'yes'

        config['bitbucket.org'] = {}

        config['bitbucket.org']['User'] = 'hg'

        config['topsecret.server.com'] = {}

        config['topsecret.server.com']['Host Port'] = '50022'

        config['topsecret.server.com']['ForwardX11'] = 'no'

        

        with open('example.ini', 'w') as configfile:

           config.write(configfile)

        
从配置文件中读出内容:

       import configparser

        config = configparser.ConfigParser()

        print(config.sections())

        print(config.read('example.ini'))

        print(config.sections())

        print(config['bitbucket.org']['User'])

        for key in config['DEFAULT']:

            print(key)

        结果是:


       []

        ['example.ini']

        ['bitbucket.org', 'topsecret.server.com']

        hg

        serveraliveinterval

        compression

        compressionlevel

        forwardx11

configparser增删改查语法

        import configparser

        config = configparser.ConfigParser()

        config.read('example.ini')

        

        # ########## 读 ##########

        #secs = config.sections()

        #print(secs)

        #options = config.options('bitbucket.org')

        #print(options)

        

        #item_list = config.items('bitbucket.org')

        #print(item_list)

        

        #val = config.get('bitbucket.org','user')

        #val = config.getint('bitbucket.org','compressionlevel')

        #print(val)

        

        # ########## 改写 ##########

        #sec = config.remove_section('bitbucket.org')

        #config.write(open('new_example.ini', "w"))

        

        #secs = config.has_section('bitbucket')

        #config.add_section('bitbucket')

        #config.write(open('example.cfg', "w"))

        

        

        #config.set('bitbucket.org','user','shuoming')

        #config.write(open('new_example.cfg', "w"))

        

        #config.remove_option('bitbucket.org','user')

        #config.write(open('new_example.cfg', "w"))

        


----------------------------接 内置模块(四)---------------------------

你可能感兴趣的:(xml,python,configparser,shelve)