python接口自动化之ConfigParser配置文件的使用详解

(编辑:jimmy 日期: 2024/9/22 浏览:2)

前言:目前我们使用的绝大多数计算机程序,无论是办公软件,浏览器,甚至游戏、视频都是通过菜单界面系统配置的,它几乎成了我们使用机器的默认方式。而在python中,也有这样的一个配置模块可以把代码可配置化。

什么是配置文件

"text-align: center">python接口自动化之ConfigParser配置文件的使用详解

"color: #ff0000">读取配置文件

"htmlcode">

from configparser import ConfigParser

# 创建一个操作配置文件的对象(文件解析对象)
conf = ConfigParser()

# 读取配置文件
conf.read("conf.ini", encoding="utf8")
# 获取所有section
res2 = conf.sections()
print("这是res2:{}\n".format(res2))
# 获取对应section下的option
res3 = conf.options("logging")
print("这是res3:{}\n".format(res3))
# 获取对应section下的所有键值对
res4 = conf.items("logging")
print("这是res4:{}\n".format(res4))
# get方法:读取出来的内容,都是字符串
res5 = conf.get("logging", "level")
print("这是res5:{}".format(res5), type(res5))
# getint方法:读取出来的内容,都是int类型
res6 = conf.getint("mysql", "port")
print("\n这是res6:{}".format(res6), type(res6))

"color: #ff0000">写入配置文件

"htmlcode">

from configparser import ConfigParser

# 创建一个操作配置文件的对象(文件解析对象)
conf = ConfigParser()
conf.add_section('test')
conf.set('test', 'name', 'Amy')
conf.write(open('conf.ini', "a", encoding="utf-8"))

"text-align: center">python接口自动化之ConfigParser配置文件的使用详解

ConfigParser的封装

"htmlcode">

from configparser import ConfigParser


class MyConf:

  def __init__(self, filename, encoding="utf8"):
    self.filename = filename
    self.encoding = encoding
    self.conf = ConfigParser()
    self.conf.read(filename, encoding)

  def get_str(self, section, option):
    return self.conf.get(section, option)

  def get_int(self, section, option):
    return self.conf.getint(section, option)

  def get_float(self, section, option):
    return self.conf.getfloat(section, option)

  def get_bool(self, section, option):

  def write_data(self, section, option, value):
    self.conf.set(section, option, value)
    self.conf.write(open(self.filename, "a", encoding=self.encoding))
    

if __name__ == '__main__':
  print(conf.get_str("conf.ini", "test","name"))	# 测试

总结

一句话新闻

Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。