日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

Python庫configparser教程

系統 2226 0

文章目錄

    • 前言
    • 初探configparser
      • 配置文件
      • 讀入配置:
      • 讀取數據
    • Section
      • Section增加
      • Section檢索
      • Section刪除
    • 高級操作
        • 單個option對應多行值
        • 單個option無對應值
        • Interpolation 插值
          • BasicInterpolation
          • ExtendedInterpolation
    • 總結

前言

configparser是Python中的一個配置文件解析庫,可以讀取配置文件中的變量和值。配置文件有什么作用呢?作用就是當你寫程序的時候,有一些固定的值,但這些值雖然暫時不會更改,但是并不確定以后會不會改變。
例如:在你的程序中有一個變量 price = 100 為定值,但是可能一段時間后 price = 200 那么你將如何改變?也許你可以手動一個個改,或者稍微效率高點的使用編輯器的替換功能(但是這樣難免保證不小心把其他變量也替換了)。這時候配置文件就有很大作用了,當你需要改變這些變量時,只需要更改配置文件,就可以輕松改變程序中所有值了。
下面,我們來開始了解一下configparser模塊吧!


初探configparser

配置文件

首先我們需要新建一個配置文件,在Windows中一般取后綴名為 .ini ,當然你也可以取其他的名字 .cfg .txt 都行。好了,我們就新建一個 demo.ini 吧!現在我們朝它寫入一些內容:

            
              [DEFAULT]
User =Lee
Date=2019-05-16
WeekDay=4
IsWorkDay=True

            
          

這里我們定義了一個 Section 名為 DEFAULT ,里面的字段分別為:

  • User
  • Date
  • WeekDay
  • IsWorkDay

讀入配置:

接下來,我們先導入 configparser ,并定義一個 ConfigParser

            
              
                import
              
               configparser
parser 
              
                =
              
               configparser
              
                .
              
              ConfigParser
              
                (
              
              
                )
              
            
          

接下來讀入配置文件

            
              configPath 
              
                =
              
              
                './demo.ini'
              
              
parser
              
                .
              
              read
              
                (
              
              configPath
              
                )
              
            
          

這里是從配置文件中讀取,還有其他操作:

  • .read_dict(dictionary :從字典中讀取。
  • .read_string(string) :從字符串中讀取。
  • .read_file(f) :從文件指針中讀取。eg: parser.read_file(open('./demo.ini'))

讀取數據

讀取數據可以使用類似字典 dict 的方法:

            
              
                >>
              
              
                >
              
              parser
              
                [
              
              
                'DEFAULT'
              
              
                ]
              
              
                [
              
              
                'User'
              
              
                ]
              
              
                'Lee'
              
              
                # 等價于
              
              
                >>
              
              
                >
              
              parser
              
                [
              
              
                'DEFAULT'
              
              
                ]
              
              
                [
              
              
                'user'
              
              
                ]
              
              
                'Lee'
              
            
          

這里我們可以發現,文件存儲的形式相當于一個字典,鍵名叫作 option ,并且 DEFAULT 段中的鍵名 User 不區分大小寫 ,但是段名 DEFAULT 還是 區分大小寫 的。
這里我們要注意的是,文件中的所有變量都是默認字符串形式,讀取出來的類型都是字符串,對于其他類型的變量,我們可以對其進行轉換,或者使用內置的方法,例如 WeekDay

            
              
                >>
              
              
                >
              
              parser
              
                .
              
              getint
              
                (
              
              
                'DEFAULT'
              
              
                ,
              
              
                'WeekDay'
              
              
                )
              
              
                4
              
            
          

對于 boolean 型變量,可以i使用 getboolean 方法:

            
              
                >>
              
              
                >
              
              parser
              
                .
              
              getboolean
              
                (
              
              
                "DEFAULT"
              
              
                ,
              
              
                "IsWorkDay"
              
              
                )
              
              
                True
              
            
          

類似的還有 .getfloat(section, option) 返回float類型

同樣也可以使用 get() 方法取字段中的 option

            
              
                >>
              
              
                >
              
              parser
              
                .
              
              get
              
                (
              
              
                "DEFAULT"
              
              
                ,
              
              
                "IsWorkDay"
              
              
                )
              
              
                'True'
              
            
          

這里比較推薦使用 get() 方法,因為字段中不存在某個 option 時,使用類似字典的方法會報錯,而使用 get() 方法就可以設置 fallback 值,表示當不存在時返回的默認值。

            
              
                >>
              
              
                >
              
              parser
              
                [
              
              
                'DEFAULT'
              
              
                ]
              
              
                [
              
              
                'does-not-exist'
              
              
                ]
              
              
Traceback 
              
                (
              
              most recent call last
              
                )
              
              
                :
              
              
                .
              
              
                .
              
              
                .
              
              
KeyError
              
                :
              
              
                'does-not-exist'
              
              
                >>
              
              
                >
              
              parser
              
                .
              
              get
              
                (
              
              
                "DEFAULT"
              
              
                ,
              
              
                "does-not-exist"
              
              
                ,
              
               fallback
              
                =
              
              
                ""
              
              
                )
              
              
                ''
              
            
          

這里我們設置了 fallback 為空,因此當 option 不存在時,返回空串而不是報錯。


Section

Section增加

接下來我們要新增一個 Section 段,我們可以直接在配置文件中加入:

            
              
                [
              
              DEFAULT
              
                ]
              
              
User 
              
                =
              
              Lee
Date
              
                =
              
              
                2019
              
              
                -
              
              
                05
              
              
                -
              
              
                16
              
              
WeekDay
              
                =
              
              
                4
              
              
IsWorkDay
              
                =
              
              
                True
              
              
                # 新增Section1
              
              
                [
              
              Section1
              
                ]
              
              
Year
              
                =
              
              
                2019
              
              
Month
              
                =
              
              
                5
              
              
Day
              
                =
              
              
                16
              
              
Language
              
                =
              
              Pythoon
FilePath
              
                =
              
              
                .
              
              
                /
              
              demo
              
                .
              
              ini

            
          

也可以在代碼中寫入:

            
              parser
              
                [
              
              
                'Section1'
              
              
                ]
              
              
                =
              
              
                {
              
              
                "Year"
              
              
                :
              
              
                2019
              
              
                ,
              
              
                "Month"
              
              
                :
              
              
                5
              
              
                ,
              
              
                "Day"
              
              
                :
              
              
                16
              
              
                ,
              
              
                "Language"
              
              
                :
              
              
                "Python"
              
              
                ,
              
              
                "FilePath"
              
              
                :
              
              
                "./demo.ini"
              
              
                }
              
            
          

這里雖然我們寫入的時候 Year Month Day 都為數值類型,但是默認是字符串,因此當你輸出的時候還是字符串:

            
              
                >>
              
              
                >
              
              parser
              
                .
              
              get
              
                (
              
              
                'Section1'
              
              
                ,
              
              
                'Year'
              
              
                )
              
              
                '2019'
              
            
          

我們還可以這樣寫入:

            
              
                >>
              
              
                >
              
              parser
              
                .
              
              add_section
              
                (
              
              
                'Section1'
              
              
                )
              
              
                >>
              
              
                >
              
              parser
              
                .
              
              
                set
              
              
                (
              
              
                "Section1"
              
              
                ,
              
              
                "Year"
              
              
                ,
              
              
                "2019"
              
              
                )
              
              
                # 注意這里option的值必須為字符串類型
              
            
          

Section檢索

我們可以查看是否存在 Section

            
              
                >>
              
              
                >
              
              parser
              
                .
              
              has_section
              
                (
              
              
                'Section1'
              
              
                )
              
              
                True
              
            
          

同理也可以查看是否存在 option

            
              
                >>
              
              
                >
              
              parser
              
                .
              
              has_option
              
                (
              
              
                'Section1'
              
              
                ,
              
              
                'Year'
              
              
                )
              
              
                True
              
            
          

我們可以查看目前有幾個 Section

            
              
                >>
              
              
                >
              
              parser
              
                .
              
              sections
              
                (
              
              
                )
              
              
                [
              
              
                'Section1'
              
              
                ]
              
            
          

怎么沒有 DEFAULT ?
因為 DEFAULT 是配置文件中的默認字段,不屬于一個 Section
查看 Section 中的 option

            
              
                >>
              
              
                >
              
              parser
              
                .
              
              options
              
                (
              
              
                'Section1'
              
              
                )
              
              
                [
              
              
                'year'
              
              
                ,
              
              
                'month'
              
              
                ,
              
              
                'day'
              
              
                ,
              
              
                'language'
              
              
                ,
              
              
                'filepath'
              
              
                ,
              
              
                'user'
              
              
                ,
              
              
                'date'
              
              
                ,
              
              
                'weekday'
              
              
                ,
              
              
                'isworkday'
              
              
                ]
              
            
          

你會發現,它不止返回了 Section 中的 option ,還返回了 DEFAULT 中的 option ,并且這個 DEFAULT 你無法在代碼中刪除它。
我們在文件內容中將其改名為 Section0 :

            
              
                [
              
              Section0
              
                ]
              
              
User
              
                =
              
              Lee
Date
              
                =
              
              
                2019
              
              
                -
              
              
                05
              
              
                -
              
              
                16
              
              
WeekDay
              
                =
              
              
                4
              
              
IsWorkDay
              
                =
              
              
                True
              
              
                [
              
              Section1
              
                ]
              
              
Year
              
                =
              
              
                2019
              
              
Month
              
                =
              
              
                5
              
              
Day
              
                =
              
              
                16
              
              
Language
              
                =
              
              Pythoon
FilePath
              
                =
              
              
                .
              
              
                /
              
              demo
              
                .
              
              ini


            
          

然后

            
              
                >>
              
              
                >
              
              parser
              
                .
              
              sections
              
                (
              
              
                )
              
              
                [
              
              
                'Section0'
              
              
                ,
              
              
                'Section1'
              
              
                ]
              
              
                >>
              
              
                >
              
              parser
              
                .
              
              options
              
                (
              
              
                'Section1'
              
              
                )
              
              
                [
              
              
                'year'
              
              
                ,
              
              
                'month'
              
              
                ,
              
              
                'day'
              
              
                ,
              
              
                'language'
              
              
                ,
              
              
                'filepath'
              
              
                ]
              
            
          

好了這樣舒服多了。
還可以查看某個 Section 中的 option 對:

            
              
                >>
              
              
                >
              
              parser
              
                .
              
              items
              
                (
              
              
                "Section1"
              
              
                )
              
              
                [
              
              
                (
              
              
                'year'
              
              
                ,
              
              
                '2019'
              
              
                )
              
              
                ,
              
              
                (
              
              
                'month'
              
              
                ,
              
              
                '5'
              
              
                )
              
              
                ,
              
              
                (
              
              
                'day'
              
              
                ,
              
              
                '16'
              
              
                )
              
              
                ,
              
              
                (
              
              
                'language'
              
              
                ,
              
              
                'Pythoon'
              
              
                )
              
              
                ,
              
              
                (
              
              
                'filepath'
              
              
                ,
              
              
                './demo.ini'
              
              
                )
              
              
                ]
              
            
          

Section刪除

刪除一個 Section 可以使用 .remove_section() 方法:

            
              
                >>
              
              
                >
              
              parser
              
                .
              
              remove_section
              
                (
              
              
                "Section1"
              
              
                )
              
              
                True
              
            
          

還有其他類似操作:

  • .popitem() ,刪除最上面的一個 Section 并返回,如果空則報錯(類似棧的彈出)
  • .clear() ,刪除所有 Section
  • .remove_option(section, option) 刪除某個 Section 中的 option

高級操作

單個option對應多行值

更改下配置文件中 Section0 的內容

            
              
                [
              
              Section0
              
                ]
              
              
User
              
                =
              
              Lee 
  James 
              
                # 注意前面必須縮進!
              
              
  Michael
Date
              
                =
              
              
                2019
              
              
                -
              
              
                05
              
              
                -
              
              
                16
              
              
WeekDay
              
                =
              
              
                4
              
              
IsWorkDay
              
                =
              
              
                True
              
            
          

使得單個 option 對應多個值 Lee``James``Michael

            
              
                >>
              
              
                >
              
              
                print
              
              
                (
              
              parser
              
                [
              
              
                "Section0"
              
              
                ]
              
              
                [
              
              
                "user"
              
              
                ]
              
              
                )
              
              
Lee
James
Michael

            
          

單個option無對應值

            
              
                [
              
              Section0
              
                ]
              
              
User
              
                =
              
              Lee 
  James # 注意前面必須縮進!
  Michael
Date
              
                =
              
              
                2019
              
              
                -
              
              
                05
              
              
                -
              
              
                16
              
              
Tomorrow   # 無對應值
WeekDay
              
                =
              
              
                4
              
              
Today     # 無對應值
IsWorkDay
              
                =
              
              True

            
          

這里我們增加了兩個無對應值的 option ,但是注意:
開頭必須設置 allow_no_value=True

            
              parser 
              
                =
              
               configparser
              
                .
              
              ConfigParser
              
                (
              
              allow_no_value
              
                =
              
              
                True
              
              
                )
              
            
          

然后,讀取所有 option

            
              
                >>
              
              
                >
              
              parser
              
                .
              
              options
              
                (
              
              
                "Section0"
              
              
                )
              
              
                [
              
              
                'user'
              
              
                ,
              
              
                'date'
              
              
                ,
              
              
                'tomorrow'
              
              
                ,
              
              
                'weekday'
              
              
                ,
              
              
                'today'
              
              
                ,
              
              
                'isworkday'
              
              
                ]
              
              
                >>
              
              
                >
              
              parser
              
                .
              
              get
              
                (
              
              
                "Section0"
              
              
                ,
              
              
                "Tomorrow"
              
              
                )
              
              
                # 輸出空
              
            
          

Interpolation 插值

BasicInterpolation

BasicInterpolation 是默認的 Interpolation 類,我們可以定義類似占位符一樣的形式來進行插值操作,我們先修改 Section0 如下:

            
              
                [
              
              Section0
              
                ]
              
              
Year
              
                =
              
              
                2019
              
              
Month
              
                =
              
              
                5
              
              
Day
              
                =
              
              
                16
              
              
Date
              
                =
              
              
                %
              
              
                (
              
              Year
              
                )
              
              s
              
                -
              
              
                %
              
              
                (
              
              Month
              
                )
              
              s
              
                -
              
              
                %
              
              
                (
              
              Day
              
                )
              
              s

            
          
            
              
                >>
              
              
                >
              
              parser
              
                .
              
              get
              
                (
              
              
                "Section0"
              
              
                ,
              
              
                "Date"
              
              
                )
              
              
                '2019-5-16'
              
            
          

這里我們利用的是類似C語言中的 %s ,形式為 %(option)s

            
              parser
              
                .
              
              get
              
                (
              
              
                "Section0"
              
              
                ,
              
              
                "Date"
              
              
                ,
              
               raw
              
                =
              
              
                True
              
              
                )
              
              
                # 許多方法都有這個raw參數來輸出raw字符串
              
            
          

或者在開頭定義 parser 時設置:

            
              parser 
              
                =
              
               ConfigParser
              
                (
              
              interpolation 
              
                =
              
              
                None
              
              
                )
              
            
          

輸出則變成:

            
              
                >>
              
              
                >
              
              parser
              
                .
              
              get
              
                (
              
              
                "Section0"
              
              
                ,
              
              
                "Date"
              
              
                )
              
              
                '%(Year)s-%(Month)s-%(Day)s'
              
            
          
ExtendedInterpolation

或者我們可以使用 ExtendedInterpolation()
修改 Section0 如下:

            
              
                [
              
              Section0
              
                ]
              
              
Year
              
                =
              
              
                2019
              
              
Month
              
                =
              
              
                5
              
              
Day
              
                =
              
              
                16
              
              
Date
              
                =
              
              $
              
                {
              
              Year
              
                }
              
              
                -
              
              $
              
                {
              
              Month
              
                }
              
              
                -
              
              $
              
                {
              
              Day
              
                }
              
            
          

得到同樣的效果

            
              
                >>
              
              
                >
              
              parser
              
                .
              
              get
              
                (
              
              
                "Section0"
              
              
                ,
              
              
                "Date"
              
              
                )
              
              
                '2019-5-16'
              
            
          

注意這時候格式是: ${section:option} ,也就是可以設置某個 Section 中的某個 option ,即可以使用別的段中的 option ,比如我們修改文件內容如下:

            
              
                [
              
              Section0
              
                ]
              
              
Date
              
                =
              
              $
              
                {
              
              Section1
              
                :
              
              Year
              
                }
              
              
                -
              
              $
              
                {
              
              Section1
              
                :
              
              Month
              
                }
              
              
                -
              
              $
              
                {
              
              Section1
              
                :
              
              Day
              
                }
              
              
                [
              
              Section1
              
                ]
              
              
Year
              
                =
              
              
                2019
              
              
Month
              
                =
              
              
                5
              
              
Day
              
                =
              
              
                16
              
            
          

一樣的結果:

            
              
                >>
              
              
                >
              
              parser
              
                .
              
              get
              
                (
              
              
                "Section0"
              
              
                ,
              
              
                "Date"
              
              
                )
              
              
                '2019-5-16'
              
            
          

總結

.ini 文件中:

  • 文件中的任何變量形式都是字符串
  • option 對可以用 = : 來表示鍵值對應
  • option 鍵名不區分大小寫, Section 名區分
  • 文件中多余的空白符會被默認去掉
  • option 的值可以多行,也可為空
  • 注釋以 # 或者 ; 開頭

更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 千阳县| 长顺县| 泽普县| 望都县| 石泉县| 蒙自县| 田阳县| 比如县| 眉山市| 图们市| 新乡县| 磴口县| 姚安县| 青冈县| 绵竹市| 吉安市| 通海县| 公主岭市| 南陵县| 桑植县| 平安县| 灵寿县| 桦川县| 镇江市| 金坛市| 杨浦区| 临汾市| 屯留县| 平利县| 淳化县| 龙岩市| 齐齐哈尔市| 四会市| 永定县| 察哈| 大英县| 左权县| 河东区| 晋城| 巫溪县| 威远县|