Applicable to configuration ini File format , Can contain one or more sections (section), Each section can have multiple parameters ( key = value ).
import configparser
# Library import
config = configparser.ConfigParser()
# Instantiate a config object
config["seg1"] = {'a': '20',
'b': 'yes',
'c': '9',
'd':'ok'}
config['seg2'] = {'e':'233'}
#seg1,seg2 yes config This one section The name of
# Similar to the form of an operational dictionary
with open('example.ini', 'w') as configfile:
config.write(configfile)
# take config Object write to file
So there is a example.ini file . Open it with notepad in the following form
import configparser
# Library import
config = configparser.ConfigParser()
# Instantiate an object
print(config.sections())
#[]
# here config Objects have no segment
config.read('example.ini')
print(config.sections())
#['seg1', 'seg2']
# Read what we wrote before ini file , There are two segment
'seg1' in config
#True
'seg3' in config
#False
'''
Judge a by name segment Is here or not config Inside
'''
config['seg1']
# <Section: seg1>
config['seg1']['a']
# '20'
config.get('seg1','a')
# '20'
'''
Read config The value of the inside
'''
for key in config['seg1']:
print(key)
'''
a
b
c
d
'''
config.options('seg1')
'''
['a', 'b', 'c', 'd']
'''
# One of them segment Everything in it key
config.items('seg1')
# [('a', '20'), ('b', 'yes'), ('c', '9'), ('d', 'ok')]
# One of them segment All key value pairs inside
config.add_section('seg3')
# add to segment
config.remove_section('seg2')
# remove segment
config.remove_option('seg1','a')
# Remove an item
config.set('seg3','a','12345')
# Set an item
with open('example2.ini','w') as f:
config.write(f)
And what you get is