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') // 獲取sections下所有key值

        #print(options)

        

        #item_list = config.items('bitbucket.org') // 獲取sections下所有items

        #print(item_list)

        

        #val = config.get('bitbucket.org','user')  // 在sections 下找到某key值

        #val = config.getint('bitbucket.org','compressionlevel') // 先get 後int,即將int類型的

            字符串轉換成int類型

        #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"))

        


----------------------------接 內置模塊(四)---------------------------

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章