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

Source: Internet
Author: User

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:

Related Article

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.