How to use Python parsing module (ConfigParser)

Many softwares have configuration files. Today I will introduce the usage of python ConfigParser module to parse configuration files

The contents of the test configuration file test.conf are as follows:

The code is as follows:
[first]
w = 2
v: 3
c = 11-3

[second]

sw=4
test: hello

There are two areas in the test configuration file, first and second, and intentionally add some spaces and line breaks.

The following analysis:

Code is as follows:
>>> import ConfigParser
>>> conf = ConfigParser.ConfigParser ()
>>> conf.read ('test.conf')
['test.conf']
>>> conf.sections () #Get all areas
['first', 'second']
>>> for sn in conf.sections ():
... print conf.options (sn) #Print out all the attributes of each area
... 
['w', 'v ',' c ']
[' sw ',' test ']

Get the attribute value of each area:

The code is as follows:
for sn in conf.sections ():
    print sn, '->'
    for attr in conf.options (sn):
       print attr, '=', conf.get (sn, attr)

Output:

The code is as follows:
first->
w = 2
v = 3
c = 11-3
second->
sw = 4
test = hello

Well, the above is the basic use process, the following is 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()

The above is to write configuration information to test2.ini.

Guess you like

Origin www.cnblogs.com/victory-0315/p/12753695.html