This article describes how to use the ConfigParser module of Python to read and write the ini configuration file. ConfigParser includes some basic operations on the section of ini, which makes it easy to rewrite ini, you can refer to the databases or other things that require dynamic configuration when using Python for development. it is very troublesome to change the hard code in it each time. Python uses ConfigParser, a module that reads configuration files, for ease of use.
Ini file
Ini configuration file format:
Read the configuration file:
Import ConfigParserconf = ConfigParser. configParser () conf. read ('dbconf. ini ') # file path name = conf. get ("section1", "name") # obtain the option value of the specified section print namesex = conf. get ("section1", "sex") # obtain the sex value of section1 print age
Output:
jhaomale
Write the configuration file:
Import ConfigParserconf = ConfigParser. configParser () conf. read ('dbconf. ini ') conf. set ("section1", "name", "jhao104") # Modify the optionconf of the specified section. set ("section1", "age", "21") # Add optionconf for the specified section. add_section ("section3") # Add sectionconf. set ("section3", "site", "oschina.net") # write optionconf to the newly added section. write (open ('dbconf. ini ', 'w '))
Output: