【學習筆記】配置ConfigParser模塊

前言

配置文件以conf ini結尾,可以通過修改參數進行結果的修改

1.寫配置文件

右鍵——New——File

[MYSQL]
# 數據表
host = 127.0.0.1
poxy = 3099
name = StudentData

[MYSQL]是section,host是option,127.0.0.1是value

2.讀配置文件

tips:
ctrl+左鍵可以看到模塊的源碼,從__init__函數可以看到創建對象所需要的參數,

1)創建ConfigParser對象

cf = configparser.ConfigParser()

2)基礎讀取配置文件函數

read(filename)—直接讀取文件內容

read 函數打開文件類似於open,如果有中文最好設置成UTF-8

cf.read("test.conf",encoding = "UTF-8")
get(section,option) —得到section中option的值,返回爲string類型
res = cf.get("StudentName","stu_1")
print(res)

這個方法和get有同樣的效果,讀取出來類型都是字符串

res = cf["StudentName"]["stu_1"]
print(res)

可以使用eval()函數使他保持原來的值

res = cf["MYSQL"]["poxy"]
print(type(eval(res)))

-><class 'int'>
getint(section,option)—— 得到section中option的值,返回爲int類型

類比還有getboolean()和getfloat() 函數

res = cf.getint("MYSQL","poxy")
print(type(res))

-><class 'int'>
sections() -得到所有的section,並以list的形式返回
res = cf.sections()
print(res)

->['StudentName', 'MYSQL']

類似的還有option(section)獲取option,items(section)獲取鍵值對

作業

寫一個配置類 有以下幾個函數:

  • 1:讀取整數
  • 2:讀取浮點數
  • 3:讀取布爾值
  • 4:讀取其他類型的數據 list tuple dict
  • 5:讀取字符串

TestCase

[TestCase]
#測試類
int = 1
str = Ben
float = 1.2
boolean = True
tuple = ("Hello","World")
dict = {"name":"Nancy","age":18}
list = ["Hello","World"]

作業

import configparser

class ConfigPa(object):
    def __init__(self,filename,section,option):
        self.filename = filename
        self.section = section
        self.option = option

    def read_int(self):
        cf = configparser.ConfigParser()
        cf.read(self.filename,encoding= "UTF-8")
        res = cf.getint(self.section,self.option)
        return res

    def read_float(self):
        cf = configparser.ConfigParser()
        cf.read(self.filename,encoding= "UTF-8")
        res = cf.getfloat(self.section,self.option)
        return res

    def read_boollen(self):
        cf = configparser.ConfigParser()
        cf.read(self.filename,encoding= "UTF-8")
        res = cf.getboolean(self.section,self.option)
        return res

    def read_else(self):
        cf = configparser.ConfigParser()
        cf.read(self.filename,encoding= "UTF-8")
        res = cf[str(self.section)][str(self.option)]
        return eval(res)

    def read_string(self):
        cf = configparser.ConfigParser()
        cf.read(self.filename,encoding= "UTF-8")
        res = cf.get(self.section,self.option)
        return res



if __name__ == '__main__':
     test_case = ConfigPa("test.conf","TestCase","list")
     re = test_case.read_else()
     print(re)
     print(type(re))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章