Read the ini configuration file through python
What is ini?
You can understand it as a general term for a configuration file. For example, test.conf, you can understand that it is an ini file, which generally stores some configuration information. For example, the basic information of the database, we will explain it later!
So what are the benefits of ta? Is to put some configuration information out for separate management, if there are changes in the future, you only need to change the configuration file, there is no need to modify the code.
Basic format in ini
[name, just write it according to the actual situation, nothing particular]
Key1=value1
Key2=value2
Read operation is carried out through ConfigParser module in python
Actual combat
Demo scenario:
1. Create a database configuration file named db.conf, which contains the following contents:
[DATABASE]
Host = 127.0.0.1
Port = 3306
User = root
Passwd = vertrigo
Db = testdb
Charset = utf8
2. Read the information in python and connect to the database. The code is as follows:
Import configparser
Import mysql.connector
Class GetDB:
Def _ _ init__ (self, db_config):
Config = configparser.ConfigParser ()
Config.read (db_config)
# read and save the data in the configuration file
Self.host = config ['DATABASE'] [' host']
Self.port = config ['DATABASE'] [' port']
Self.user = config ['DATABASE'] [' user']
Self.passwd = config ['DATABASE'] [' passwd']
Self.db = config ['DATABASE'] [' db']
Self.charset = config ['DATABASE'] [' charset']
# here is the linked database
Def get_conn (self):
Try:
Conn = mysql.connector.connect (host=self.host, port=self.port, user=self.user, password=self.passwd, database=self.db, charset=self.charset)
Return conn
Except Exception as e:
Print ('% slots, e)
Sys.exit ()