Python python uses configparser to manage configuration files

Source: Internet
Author: User

Python also provides a module to manage the configuration file: Configparser, with this we can write the program at the time to write some configuration information separately to the configuration file, such as: Database connection information.


1. Format of the configuration file

The configuration file must be in a specific format: param.conf

[mysqldb]host = 127.0.0.1port = 22username = Mynamepassword = 123456[global]myroot =/home/myname/project/[input] InputDir =/home/myname/data/

The brackets "[]" are included in section. section below is a configuration content similar to Key-value.


2. Read the configuration file

The code to read the configuration file in the program is as follows:

Import configparserconfig = Configparser.configparser () config.read ("param.conf") Dbhost = Config.get (' MysqlDB ', ' Host ') Dbport = Config.get (' mysqldb ', ' port ') Dbusername = Config.get (' mysqldb ', ' username ') Dbpassword = Config.get (' MySQLdb ', ' password ')


The advantage of this is that when you need to modify the configuration, directly modify the contents of the configuration file is OK, do not need to modify the program source code. This will be very convenient and safe.


Well, I hope to help you.


--------------------------------------------------------------------------------------------------------------- ---------------------










Python python uses configparser to manage configuration files

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.