Python讀取ini配置檔案

2022-07-25 16:18:27 字數 2356 閱讀 1376

[mysql_conf]        ; 1、在ini配置檔案中,中的值被稱為section

host = 127.0.0.1 ; 3、乙個section下的鍵值對被稱為option

port = 3306 ; 4、同乙個section下也可以存在多個option,也就是多個鍵值對的配置項

username = root

password = 123456

[python] ; 2、同乙個ini檔案中可以存在多個section

version = 3.7.8

system_env = windows

from configparser import configparser

# 例項化configparser物件,來處理ini檔案

conf = configparser()

# read方法接受ini檔案路徑,也可以指定編碼格式

print(conf.read("./data/db_conf.ini", encoding="utf-8"))

# 根據section名和option的key名來獲取value

print(conf.get("mysql_conf", "host"))

# 列印所有的section名

print(conf.sections())

# 根據section名獲取所有option名,也就是鍵值對的所有key

print(conf.options("mysql_conf"))

# 判斷某個section是否存在

print(conf.has_section("name"))

# 判斷某個section下的某個option是否存在

print(conf.has_option("mysql_conf", "host"))

# _*_coding:utf-8_*_

from box import box

from configparser import configparser

"""@time : 2020/11/19 20:03

@author : carpli

@file : conf_tool.py

@desc : 讀取ini配置檔案

"""class conftool(configparser):

def __init__(self, file, encoding="utf-8"):

# 執行父類的建構函式

super().__init__()

self.read(filenames=file, encoding=encoding)

# 獲取不到section或者option,直接返回給定的預設值

def get_or_default(self, section, option, default=none):

if not self.has_section(section):

return default

elif not self.has_option(section, option):

return default

return self.get(section=section, option=option)

# ini檔案內容轉換成dict輸出

def to_dict(self):

_dict = {}

for section in self.sections():

# print(dict(conf.items("mysql_conf")))

_option_dict = dict(conf.items(section=section))

_dict.update()

return _dict

# 使用python-box模組,方便鏈式呼叫

def __getattr__(self, item):

_box = box(self.to_dict())

return getattr(_box, item)

if __name__ == '__main__':

conf = conftool(file="./data/db_conf.ini")

# 配置檔案中如沒有配置mysql登入名user欄位,則預設取root

print(conf.get_or_default("mysql_conf", "user", "root"))

print(conf.to_dict())

# 可以通過屬性呼叫的形式,獲取配置

print(conf.mysql_conf.host)

python 讀取ini配置檔案

使用配置檔案裝載一些條件,以及一些對資料庫進行操作的語句等 作為對資料處理的一些外接條件。import configparser config file r format interdoc conf config configparser.configparser config.read confi...

python讀取 ini 配置檔案

在詳解python讀取ini檔案之前,我們先說明乙個ini檔案的組成 乙個ini檔案是由多個section組成,每個section中以key vlaue形式儲存資料 然後我們來使用python讀取ini檔案中的資料 1導包 導包import configparser config configpar...

python 讀取 ini 配置檔案

關於讀取配置檔案的想法 主要是因為程式裡面通過改變變數值 達到不同的目的 如果寫死 變成常量 如果下次領導說換乙個玩法 還得去改 再重新編譯一次 開發過程中發現較關鍵的變數 最好是把它配置化 當然如果你來了 肯定也是為此 進入正題 config.ini test addr test2 addr 寫乙...