config.ini
[section] key1 = aaa key2 = bbb key3 = ccc [db2] key4 = ddd
.py
# -*- coding: utf-8 -*- from configparser import ConfigParser # 读取config.ini配置文件 def readFile(): cp = ConfigParser() cp.read("config.ini", encoding='UTF-8-sig') listSection = cp.options('section') # 获取指定section下所有的key print(listSection) # 运行结果: ['字段1', '字段2'] items = cp.items('section') # 获取指定section下的所有 key value print(items) # 运行结果:[('字段1', 'aaa'), ('字段2', 'bbb')] # 获取指定section下 key对应的value str1 = cp.get('section', 'key1') str2 = cp.get('section', 'key2') str3 = cp.get('db', 'key3') print(str1, str2, str3) # 运行结果:aaa bbb ccc # 判断是否存在 section或对应的key print(cp.has_section('db')) # 运行结果:True print(cp.has_option('db', 'key4')) # 运行结果:False # 删除section cp.remove_section('db') cp.write(open('config.ini', 'w')) # 删除section对应的key cp.remove_option('db', 'key3') cp.write(open('config.ini', 'w')) # 写入config.ini配置文件 def writeFile(): cp = ConfigParser() # 添加section cp.add_section('db1') # 创建section db1 cp.add_section('db2') # 创建section db2 cp.set('db1', 'key1', 'value1') # 添加 key1=value1 到 db1下 cp.set('db1', 'key2', 'value2') cp.set('db1', 'key3', 'value3') cp.set('db2', 'key4', 'value4') # 添加 key4=value4 到 db2下 cp.write(open('config.ini', 'w')) # 写入文件并保存
写入后的config.ini
[db1] key1 = value1 key2 = value2 key3 = value3 [db2] key4 = value4