Python学习(6):Config文件读取写入以及删除

配置文件示例: config.ini

[environment]
browser = 1
switch = 1

[test]
url = http://baidu.com

[prod]
url = http://google.com

  1. 读取写入配置文件
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)

  1. 删除配置文件内容
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")
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.remove_option(section,key)
    with open(config_path, 'w', encoding='utf-8')as f:
        config.write(f)

你可能感兴趣的:(Python学习(6):Config文件读取写入以及删除)