python 读取ini配置文件

一:ini文件的组成

一个ini文件由多个section组成,每个section以key=value的形式来存储数据,如下示例

[database]
host=192.168.124.16
user=root
pwd=123456
db=classify
port=3306
charset=utf8
[log]
logpath=log

section:database  log

key:host  user  pwd等

value:192.168.124.16   root    123456等

二:读取ini配置文件

import os
import configparser


class ReadConfig:
    def __init__(self, file_path):
        self.config_path = ""
        if os.path.isfile(file_path):
            self.config_path = file_path
            print("找到了", self.config_path)
        else:
            root_dir = os.path.dirname(os.path.abspath(__file__))
            print(root_dir)
            self.config_path = os.path.join(root_dir, "config.ini")
            print(self.config_path)
        self.cf = configparser.ConfigParser()
        self.cf.read(self.config_path)

    def get_db_info(self):
        secs = self.cf.sections()
        print(secs, type(secs))
        host = self.cf.get(secs[0], "host")
        user = self.cf.get(secs[0], "user")
        pwd = self.cf.get(secs[0], "pwd")
        db = self.cf.get(secs[0], "db")
        port = self.cf.get(secs[0], "port")
        charset = self.cf.get(secs[0], "charset")
        # print("host:", host, "user:", user, "pwd:", pwd, "db:", db, "port:", port, "charset:", charset)
        return {"host:": host, "user:": user, "pwd:": pwd, "dbname:": db, "port:": port, "charset:": charset}


if __name__ == "__main__":
    config = ReadConfig("../config.ini")
    db_dict = config.get_db_info()
    print(db_dict)

可以测试,测试结果如下

找到了 ../config.ini
['database', 'log'] 
{'host:': '192.168.124.16', 'user:': 'root', 'pwd:': '123456', 'dbname:': 'classify', 'port:': '3306', 'charset:': 'utf8'}

python 读取ini配置文件_第1张图片

你可能感兴趣的:(数据库)