Python库configparser教程

系统 1560 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条评论