微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python-ConfigParser模块

ConfigParser模块在python中是用来读取配置文件,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。使用的配置文件的好处就是不用再程序中硬编码,可以是你的程序变得灵活起来。

注意:在python 3 中ConfigParser模块名已更名为configparser

函数

读取配置文件

read(filename) 直接读取ini文件内容
sections() 得到所有的section,并以列表的形式返回
options(section) 得到该section的所有option
items(section) 得到该section的所有键值对
get(section,option) 得到section中option的值,返回为string类型
getint(section,option) 得到section中option的值,返回为int类型
getfloat(section,option)得到section中option的值,返回为float类型
getboolean(section, option)得到section中option的值,返回为boolean类型

 

写入配置文件

add_section(section) 添加一个新的section
has_section(section) 判断是否有section
set( section, option, value) 对section中的option进行设置
remove_setion(section)删除一个section
remove_option(section, option)删除section中的option
write(fileobject)将内容写入配置文件

使用:

配置文件的格式如下:中括号“[]”内包含的为:section, section下面为类似于key-value的键值对的option的内容

#config.ini

[private_debug] # debug测试服务器 tester = Test environment = debug versionCode = 5.0.0 host = http://gz.test.com:810 loginHost = fronted-docker-pre2/postLogin [online_release] #release 正式服务 tester = xiao xi environment = release versionCode = 5.0.0 versionCode = v1.0 host = http://gz.live.com loginHost = frontend-docker-pre2/postLogin

ConfigParser 初始化对象

from configparser import ConfigParser
config = ConfigParser()
#读取ini配置文件内容
config.read(config.ini, encoding="utf-8")

常用方法

1.获取所有的section节点


from configparser import ConfigParser
config = ConfigParser()
#读取ini配置文件内容
config.read(config.ini, encoding="utf-8")
#获取section sec = config.sections() print(sec) #运行结果 ['private_debug', 'online_release']

2.获取section的options,即key值

from configparser import ConfigParser
config = ConfigParser()
#读取ini配置文件内容
config.read(config.ini, encoding="utf-8") opt_key = config.options("private_debug") print(opt_key) #运行结果: ['tester', 'environment', 'versioncode', 'host', 'loginhost']

 3.获取section下的option值(键值对)

from configparser import ConfigParser
config = ConfigParser()
#读取ini配置文件内容
config.read(config.ini, encoding="utf-8")
r = config.get(‘private_debug’,‘tester')

#运行结果:
test

 

 

 

参考文献:

https://www.cnblogs.com/ming5218/p/7965973.html

https://blog.csdn.net/henulwj/article/details/49174355?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.control&dist_request_id=1328627.8853.16153468533666025&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.control

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐