1. Create a Configparser file
import configparser #导入模块config = configparser.ConfigParser() #注意大小写与()config[‘DEFAULT‘] = {‘Server‘: ‘45‘, ‘Compression‘: ‘yes‘}config[‘server‘] = {‘deletehq‘:‘0‘, ‘localtime‘:‘20180706‘, ‘port‘:‘22‘}config[‘system‘] = {‘market64‘:‘xiadan1.exe‘, ‘market128‘:‘xiadan2.exe‘, ‘market256‘:‘xiadan3.exe‘ }config[‘client‘] = {}with open(‘configTest.ini‘, ‘w‘) as configfile: config.write(configfile)
or create it from a dictionary
config = configparser.ConfigParser()config.read_dict( { ‘section1‘: {‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘, ‘key3‘: ‘value3‘}, ‘section2‘: {‘keyA‘: ‘valueA‘, ‘keyB‘: ‘valueB‘, ‘keyC‘: ‘valueC‘}, ‘section3‘: {‘foo‘: ‘x‘, ‘bar‘: ‘y‘, ‘fun: ‘z‘} } )with open(‘configTest1.ini‘, ‘w‘) as configfile: config.write(configfile)
2. Read the configuration file
config.read(‘configTest.ini‘)
[DEFAULT]server = 45compression = yes[server]deletehq = 0localtime = 20180706port = 22[system]market64 = xiadan1.exemarket128 = xiadan2.exemarket256 = xiadan3.exe[client]
3. Read operations
获取所有sectionsprint(config.sections())[‘server‘, ‘system‘, ‘client‘]获取指定 section 的 keys & valuesprint(config.items(‘system‘))[(‘server‘, ‘45‘), (‘compression‘, ‘yes‘), (‘market64‘, ‘xiadan1.exe‘), (‘market128‘, ‘xiadan2.exe‘), (‘market256‘, ‘xiadan3.exe‘)] # 注意items()返回的字符串会全变成小写获取指定 section 的 keysprint(config.options(‘system‘))[‘market64‘, ‘market128‘, ‘market256‘, ‘server‘, ‘compression‘] #会打印default中的keys获取指定 key 的 valueprint(config[‘system‘][‘market64‘])xiadan1.exe
4. Check
‘section’ in config‘option’ in config[‘section‘]config.has_section[‘section‘]config.hais_option[‘section‘,‘option‘]
5. Add
config.add_section(‘section4‘) config.set(‘section4‘,‘key1‘,‘value1‘)config.write(open(‘configTest1.ini‘,‘w‘)) #写入[section4]key1 = value1
6. Delete
config.remove_option(‘section4‘,‘key1‘) #删除optionconfig.remove_section(‘section4‘) #删除section
7.[default]
[Default] generally contains the default entry for the INI format configuration file, so the Configparser section method will automatically skip it. Sections () is not available, and the Delete method is not valid for [default], but specifies that the keys & values in [default] are OK, and a special one is that has_section () is not valid and can be used in the difference between 。
Simple use of configparser under Python3