前言:目前我们使用的绝大多数计算机程序,无论是办公软件,浏览器,甚至游戏、视频都是通过菜单界面系统配置的,它几乎成了我们使用机器的默认方式。而在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"))	# 测试

总结

标签:
python接口自动化,ConfigParser配置文件

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。