前言
配置文件以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))