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