配置文件示例: config.ini
[environment]
browser = 1
switch = 1
[test]
url = http://baidu.com
[prod]
url = http://google.com
- 读取写入配置文件
import configparser
section = None
key = "new_key"
value = "new_value"
config_path = "D:\\0_python\\config\\config.ini"
config = configparser.ConfigParser()
config.read(config_path,encoding="utf-8-sig")
#获得 section-environment下的key-switch对应的value值1
switch = config.get('environment', 'switch')
if section == None and switch == str(1):
section = 'test'
elif section == None and switch == str(0):
section = 'prod'
if key is not None and value is not None:
r = config.set(section,key,value)
#必须写入保存,不然添加的内容不会被写入文件
with open(config_path, 'w', encoding='utf-8')as f:
config.write(f)