14.7.4 修改设置
ConfigParser主要通过从文件读取设置来进行配置,不过也可以填充设置,通过调用add_section()来创建一个新的节,另外调用set()可以增加或修改一个选项。
import configparser
parser = configparser.SafeConfigParser()
parser.add_section('bug_tracker')
parser.set('bug_tracker','url','http://localhost:8080/bugs')
parser.set('bug_tracker','username','dhellmann')
parser.set('bug_tracker','password','secret')
for section in parser.sections():
print(section)
for name,value in parser.items(section):
print(' {} = {!r}'.format(name,value))
所有选项都必须被设置为字符串,即使它们将被获取为整数、浮点数或布尔值。
可以分别用reamove_section()和remove_option()从ConfigParser删除节和选项。
from configparser import ConfigParser
parser = ConfigParser()
parser.read('multisection.ini')
print('Read values:\n')
for section in parser.sections():
print(section)
for name,value in parser.items(section):
print(' {} = {!r}'.format(name,value))
parser.remove_option('bug_tracker','password')
parser.remove_section('wiki')
print('\nModified values:\n')
for section in parser.sections():
print(section)
for name,value in parser.items(section):
print(' {} = {!r}'.format(name,value))
删除一节也会删除其中包含的所有选项。