Python uses the built-in ConfigParser module to read and write ini configuration files

Source: Internet
Author: User
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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.