Python USES ConfigParser to parse instances of ini configuration files

  • 2020-04-02 14:02:41
  • OfStack

Ini file is a configuration file commonly used in Windows. The main format is:


[Section1]
option1 : value1
option2 : value2

Python provides a simple module, ConfigParser, that can be used to parse files in this form. The ConfigParser module can parse key:value and key=value, for # and; The first line is automatically ignored. It's the comment line. Common functions:

ConfigParser.RawConfigParser() RawConfigParser Object Are: .sections() : Returns all available section
.addsection(sectionname) Add: section
.set(sectionname, optionname, optionvalue) : add option
.hassection(sectionname) Judge:
.options(sectionname) : return section Under the available option
.hasoption(sectionname, optionname) : judge
.read(filename) : Read the file
.wrie(filename) : will RawConfigParser Object is written to a file
.get(sectionname, optionname) : Get the value , The default is to return string type
.getfloat, .getint, .getboolean : Gets different types of return values, parameters and get The same parameter
.items(sectionname) List: section Of all the key : value
.remove(sectionname) : delete section
.remove(sectionname, option_name) : delete section Under a certain option

Demo -- generate files

$ cat ini_demo.py
# -*- coding:utf-8 -*- import ConfigParser def gen_ini():
    ftest = open('test','w')
    config_write = ConfigParser.RawConfigParser()
    config_write.add_section('Section_a')
    config_write.add_section('Section_b')
    config_write.add_section('Section_c')
    config_write.set('Section_a','option_a1','apple_a1')
    config_write.set('Section_a','option_a2','banana_a2')
    config_write.set('Section_b','option_b1','apple_b1')
    config_write.set('Section_b','option_b2','banana_b2')
    config_write.set('Section_c','option_c1','apple_c1')
    config_write.set('Section_c','option_c2','banana_c2')  
    config_write.write(ftest)
    ftest.close() if __name__ == "__main__":
    gen_ini()

The final generated file is:

$ cat test
[Section_a]
option_a1 = apple_a1
option_a2 = banana_a2 [Section_c]
option_c2 = banana_c2
option_c1 = apple_c1 [Section_b]
option_b1 = apple_b1
option_b2 = banana_b2
Demo -- Read the file def read_ini():
    config_read = ConfigParser.RawConfigParser()
    config_read.read('test')
    print config_read.sections()
    print config_read.items('Section_a')
    print config_read.get('Section_a','option_a1')

The final result is:

['Section_a', 'Section_c', 'Section_b']
[('option_a2', 'banana_a2'), ('option_a1', 'apple_a1')]
apple_a1


Related articles: