Python uses the built-in ConfigParser module to read and write the ini configuration file,
When using Python for development, databases or other things that require dynamic configuration are often used. It is very troublesome to change hard encoding 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: