Application of the ConfigParser module in Python
Application of the ConfigParser module in Python
The Python ConfigParser module defines three class RawConfigParser, ConfigParser, and SafeConfigParser that operate INI files. RawCnfigParser is the most basic INI File Reading Class. ConfigParser and SafeConfigParser support parsing the % (value) s variable.
The following describes how to parse an INI file through the ConfigParser class.
Configuration File settings. cfg
[DEFAULT]mykey=myvalue[section_a]key1=value1key2=value2key3=value3[section_b]key1=value1key2=value2key3=value3[db]db_host=127.0.0.1db_port=5432db_user=admindb_pass=Letmeindb_name=testdb_url = jdbc:postgresql://%(db_host)s:%(db_port)s/%(db_name)s
The test code is as follows:
# Coding: utf-8import ConfigParser, OS # Read configuration file cp = ConfigParser. configParser () cp. read (['settings. cfg ']) # obtain all ults sectionults ults = cp. defaults () print defaults # obtain all sectionssections = cp. sections () print sections # determine whether the specified section has has_db = cp. has_section ('db') print has_db # obtain the configuration information of the specified section, and only obtain the key options = cp. options ('db') print options # obtain the configuration information of the specified section and obtain the key value items = cp. items ('db') print items # obtain the configuration information of the specified section, and obtain the value db_host = cp based on the key. get ('db', 'db _ host') db_port = cp. getint ('db', 'db _ port') db_user = cp. get ('db', 'db _ user') db_pass = cp. get ('db', 'db _ pass') db_name = cp. get ('db', 'db _ name') db_url = cp. get ('db', 'db _ url') print db_host, db_port, db_name, db_user, db_pass # use the DEFAULT section value myvalue = cp. get ('db', 'mykey') print myvalue # Add a sectioncp. add_section ('section _ C') cp. set ('section _ C', 'key1', 'value111') cp. set ('section _ C', 'key2', 'value222') cp. set ('section _ C', 'key3', 'value333') cp. set ('section _ C', 'key4', 'value444') cp. write (open ("test1.cfg", "w") # Remove optioncp. remove_option ('section _ C', 'key4') # Remove sectioncp. remove_section ('section _ C') cp. write (open ("test2.cfg", "w "))