【学习笔记】配置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))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值