configparser模块用于在python中读取配置文件。配置文件的格式类似于windows下的ini配置文件,可以包含一个或多个节点(section), 每个节可以有多个参数(键=值)。使用配置文件的优点是不写程序,可以使程序更加灵活。
1、创建配置文件
配置文件一般创建在config包下,最好使用配置文件.例如,ini格式如下:
[LoginElement]#节点(section) user_name=id>logInName#id决定了如何定位它 user_password=id>password code_image=id>verifyCode code_text=id>verifyCodeInput submit=id>submitForm [mysql]#节点(section) host=id>127.0.0.1 port=id>3306 user=id>root password=id>123456
2、读取配置文件
cf=configparser.ConfigParser()#创建对象 cf.read('D:\liantuo\seleniumTest\config\LocalElement.ini',encoding='UTF-8')#读取配置文件,直接读取ini文件内容 print(cf.sections()#在ini文件中获取所有section(节点),以列表形式返回 print(cf.options("LoginElement"))#在指定的sections下获取所有options(key),以列表形式返回 print(cf.items('LoginElement'))#在指定的section下获得所有键对(key-value) print(cf.get('LoginElement','user_name'))#在section中获得option的值,返回string类型 getint(section,option)#返回int类型 getfloat(section,option)#返回float类型 getboolean(section,option)#返回boolen类型
*注:在阅读配置文件时,添加encoding='UTF-8' ,防止(UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 15: illegal multibyte sequence)
对应输出
['LoginElement','mysql'] ['user_name','user_password','code_image','code_text','submit'] [('user_name','id>logInName'),('user_password','id>password'),('code_image','id>verifyCode'),('code_text', 'id>verifyCodeInput'),('submit','id>submitForm')] id>logInName
3、重构封装
classReadIni(object): #构造函数 def__init__(self,file_name=None,node=None): ''' :paramfile_name:配置文件地址 :paramnode:节点名 ''' #容错处理 iffile_name==None: #默认地址 file_name='D:\liantuo\seleniumTest\config\LocalElement.ini' else: self.file_name=file_name ifnode==None: #默认节点 self.node="LoginElement" else: self.node=node self.cf=self.load_ini(file_name) #加载文件 defload_ini(self,file_name): cf=configparser.ConfigParser() cf.read(file_name,encoding='utf-8') returncf #获得value得值 defget_value(self,key): data=self.cf.get(self.node,key) returndata #主入口,相当于java的main方法 if__name__='__main__': #自定义 #path=r'E:\Pythonx\seleniumTest\config\testIni.ini'#注意r #read_init=ReadIni(file_name=path,node='testa')#输入新的定制配置文件地址,节点 #print(read_init.get_value('ji'))#获取value值 #默认 read_init=ReadIni()#默认配置文件地址、节点 print(read_init.get_value('user_name'))#输入key值,获得value
python学习网,免费在线学习python平台,欢迎关注!