Python库configparser教程

前言

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"}

这里虽然我们写入的时候YearMonthDay都为数值类型,但是默认是字符串,因此当你输出的时候还是字符串:

>>>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的值可以多行,也可为空
  • 注释以#或者;开头
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值