Python如何讀取ini配置文件

Python讀取ini配置文件

LocalElement.ini配置文件內容如下:

[RegisterElement]
user_email = id>register_email

Python讀取LocalElement.ini配置文件的程序如下:

在這裏插入圖片描述

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''=================================================
@Project -> File   :Auto_Test_Second -> read_ini.py
@IDE    :PyCharm
@Author :Beetester
@Date   :2019/9/20 22:48
@Desc   :
=================================================='''
import configparser     # 第三方庫安裝pip install configparser

class ReadIni(object):

    def __init__(self, file_name=None, node=None):
        if file_name == None:
            file_name = r"D:\Python\PycharmProjects\Auto_Test_Second\config\LocalElement.ini"
        if node == None:
            self.node = "RegisterElement"
        else:
            self.node = node
        self.cf = self.load_ini(file_name)

    def load_ini(self, file_name):
        cf = configparser.ConfigParser()
        cf.read(file_name)
        return cf

    def get_value(self, key):
        data = self.cf.get(self.node, key)
        return data

if __name__ == '__main__':
    read_init = ReadIni()
    locator = read_init.get_value('user_email')
    # 根據拆分,獲取鍵對值的鍵和值
    locatorKey = locator.split(">")[0]
    locatorValue = locator.split(">")[1]
    print(locatorKey)
    print(locatorValue)

獲取的鍵值對如下,可根據獲取的鍵/值去應用。
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章