Baidu Search: Xiao Qiang test brand
AC Group: 522720170
Click on the "Follow" button in the top right corner to subscribe to us!
Forwarding + likes = support
What is INI?
You can understand it as a generic term for a configuration file. such as test.conf, so you can understand that he is the INI file, which usually contains some configuration information. For example, the basic information of the database, we will explain!
So what are the benefits of TA? is to put some configuration information to the individual management, if later changes only need to change the configuration file, no need to modify the code.
The basic format in INI
[Name, according to the actual situation to write on the line, not much attention]
Key1=value1
Key2=value2
Read operations in Python via the Configparser module
Actual combat
Demo Scenario:
1, create a database configuration file, named Db.conf, the content is as follows:
[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)
#把配置文件里的数据读取出来并保存
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 ']
#这里就是链接数据库了
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 ('%s ', E)
Sys.exit ()
Forwarding + likes = support
Baidu Search: Xiao Qiang test brand
AC Group: 522720170
Click on the "Follow" button in the top right corner to subscribe to us!
Read INI configuration file from Python