The python parsing module of ConfigParser USES methods
- 2020-04-02 13:18:19
- OfStack
The test configuration file test.conf reads as follows:
[first]
w = 2
v: 3
c =11-3
[second]
sw=4
test: hello
There are two fields, first and second, in the test configuration file, and some Spaces and newlines are deliberately added.
The following analysis:
>>> import ConfigParser
>>> conf=ConfigParser.ConfigParser()
>>> conf.read('test.conf')
['test.conf']
>>> conf.sections() # Get all the areas
['first', 'second']
>>> for sn in conf.sections():
... print conf.options(sn) # Print out all the properties for each region
...
['w', 'v', 'c']
['sw', 'test']
Get the property values for each region:
for sn in conf.sections():
print sn,'-->'
for attr in conf.options(sn):
print attr,'=',conf.get(sn,attr)
Output:
first -->
w = 2
v = 3
c = 11-3
second -->
sw = 4
test = hello
Okay, so that's the basic usage, and here's the dynamic write configuration,
cfd=open('test2.ini','w')
conf=ConfigParser.ConfigParser()
conf.add_section('test') #add a section
conf.set('test','run','false')
conf.set('test','set',1)
conf.write(cfd)
cfd.close()
Above, write configuration information to test2.ini.