第三方库:configparser(py3)、configParser (py2)
.ini 文件预览
1. 导包
import configparser
conf = configparser.ConfigParser() # 类实例化
inipath = os.path.dirname(os.path.realpath(__file__)) + "/config.ini"
2. 读取内容
# 使用上面的实例 conf
# 读取配置文件
conf.read(inipath, encoding="utf8")
# 所有sections
sections = conf.sections()
# 单个值
val1 = conf.get("section1", "option1")
# val1
# section中所有options
conf.options(sections[0])
# section中所有键值对
items = conf.items(sections[0])
# 读取值为特定类型
val1 = conf.getint(sections[0],'option1') # 返回int类型
val2 = conf.getfloat(sections[0],'option1') # 返回float类型
val3 = conf.getboolean(sections[0],'option1') # 返回boolen类型
3. 添加section/键值
try:
conf.add_section("section2")
conf.set("section2", "option1", "val1")
conf.set("section2", "option2", "val2")
except configparser.DuplicateSectionError:
print("Section 'section2' already exists")
# 此时的配置保存在内存中,需要写入文件方可生效
# 写入配置文件
config.write(open(inipath, "a"))
4. 修改内容
conf.set('section1', "option1", "val_new")
conf.write(open(inipath, "r+", encoding="utf-8")) # r+模式
5. 删除内容
# 删除option
conf.remove_option(sections[0], "option1")
# 删除section
conf.remove_section(sections[1])