Python中configparser模块的使用

配置文件test.config

[PYTHON]

number=12

name=["小明",“小华”]

 

一、配置文件的组成:

section:表示要标记的不同数据的区域,用[]表示,例如以上文件的PYTHON

option:相当于字典中的key ,例如以上文件的number、name

value:相当于字典中的value

注意:从配置文件获取到的都是字符串

 

二、读取config配置文件:

import configparser
cf= configparser.ConfigParser()
cf.read("test.config",encoding='utf-8')

 

三、获取value值的方法:

方法一:

res = cf['PYTHON']['name']

 方法二:

res=cf.get('PYTHON','name')

 

四、ConfigParser对象的其他方法,如:

sections() #获取ini文件内所有的section,以列表形式返回['logging', 'mysql']
options(sections) #获取指定sections下所有options ,以列表形式返回['host', 'port', 'user', 'password']
items(sections) #获取指定section下所有的键值对,[('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')]
get(section, option) #获取section中option的值,返回为string类型
add_section(section) #添加一个section
remove_option(section, option)
remove_section(section)
set(section, option, value)#修改配置文件中的值
配置文件ini如下:
[logging]
level = 20
server = 10.237.102.55

[mysql]
host=127.0.0.1
port=3306
user=root
password=123456

  

posted @ 2020-10-12 17:12  HM_mei  阅读(13)  评论(0)    收藏  举报