安装configParser
pip install configparser
读取的配置文件格式要求
[config]
name = ConfigParser
function = readConfigFileAndGetValue
version = V1.0
案例1:读取一个文件
import configparser
cp = configparser.ConfigParser()
cp.read("config.ini")
name = cp.get('config', 'name')
function = cp.get('config', 'function')
version = cp.get('config', 'version')
print(name, function, version)
案例2:读取多个文件
[config]
name2 = test
function1 = 333
[req]
version = 4
import configparser
cp = configparser.ConfigParser()
cp.read(["config.ini", 'config2.ini'])
name = cp.get('config', 'name')
function = cp.get('config', 'function')
version = cp.get('config', 'version')
version2 = cp.get('req', 'version')
name2 = cp.get('config', 'name2')
print(name, function, version, name2, version2)
案例3:修改配置文件
import configparser
from datetime import datetime
cp = configparser.ConfigParser()
cp.read("config.ini")
if not cp.has_section('date'):
cp.add_section("date")
cp.set("date", "today", datetime.strftime(datetime.now(), '%Y-%m-%d'))
cp.set("config", "version", "V2.0")
with open('config.ini', 'w+') as f:
cp.write(f)
修改之后的config.ini如下:
[config]
name = ConfigParser
function = readConfigFileAndGetValue
version = V2.0
[date]
today = 2022-03-21
案例4: 获取该配置文件的所有section和option
import configparser
from datetime import datetime
cp = configparser.ConfigParser()
cp.read("config.ini")
sections = cp.sections()
print("all sections: " + str(sections))
for section in sections:
print(section, cp.options(section))
获取的结果:
all sections: ['config', 'date']
config ['name', 'function', 'version']
date ['today']
案例5:删除某些section和option
import configparser
from datetime import datetime
cp = configparser.ConfigParser()
cp.read("config.ini")
cp.remove_section('date')
cp.remove_option('config', 'name')
cp.set('config', 'version', 'V3.0')
with open('config3.ini', 'w+') as f:
cp.write(f)
删除后的结果:
[config]
function = readConfigFileAndGetValue
version = V3.0
|