Python——模块——配置模块(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类型

二.写入

        add_section(section) 添加一个新的section 

        set(section, option, value) 对section中的option进行设置

        conf.write() 

三、代码示例

1、配置文件样式

[db1]
conn = localhost
port = 3306
user = root
password = 123456
dbname = test
 
[db2]
conn = localhost
port = 3306
user = root
password = 123456
dbname = test1

2、读配置

conf = configparser.ConfigParser()
conf.read(filenames=p + r'\config.ini',encoding='UTF-8')
#列出所有section
conf.sections()
#输出 ['db1', 'db2']
#列出指定section中的option
conf.options('db1')
 #输出 ['conn', 'port', 'user', 'password', 'dbname']
#列出指定区的所有键值
conf.items('db1')
#输出 [('conn', 'localhost'), ('port', '3306'), ('user', 'root'), ('password', '123456'), ('dbname', 'test')]
#获取指定section中指定键的值
conf.get('db1','conn')
#输出 localhost

3、写配置项

conf = configparser.ConfigParser()
conf.read(filenames=p + r'\config.ini',encoding='UTF-8')
conf.sections('db3')
#增加section
conf.set('db3','conn','127.0.0.1')
#设置增加section的option值
conf.set('db3','conn','localhost')
#更新指定section的option值
conf.write(open('conf.ini','w'))
#保存到配置文件

 

posted @ 2019-04-23 08:03  澄心元素  阅读(576)  评论(0编辑  收藏  举报