python读取配置文件

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python读取配置文件

888米兔   2022-06-03 我要评论

前言:

最近在接触利用python来写测试框架,本人也是个刚接触python,所以是个小菜鸟,今天开始,一点点的记录学习中的积累,方便以后的学习以及回顾,也希望能帮助跟我一样的小菜鸟们一步步的成长起来。那么,下面就不废话了,直接进入今天的主题。

配置文件作为一种可读性很好的格式,非常适用于存储程序中的配置数据。 在每个配置文件中,配置数据会被分组(比如“config”和 “cmd”)。 每个分组在其中指定对应的各个变量值。

如下:

#  定义config分组
[config]
platformName=Android
appPackage=com.romwe
appActivity=com.romwe.SplashActivity

#  定义cmd分组
[cmd]
viewPhone=adb devices
startServer=adb start-server
stopServer=adb kill-server

#  定义log分组
[log]
log_error=true

基本的读取操作:

  • -read(filename)               直接读取文件内容
  • -sections()                      得到所有的section,并以列表的形式返回
  • -options(section)            得到该section的所有option
  • -items(section)                得到该section的所有键值对
  • -get(section,option)        得到section中option的值,返回为string类型
  • -getint(section,option)    得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

在对配置文件进行读写操作前,我们需要先进行以下两个操作:

1、实例化ConfigParser对象:

#  实例化configParser对象
cf = configparser.ConfigParser()

2、读取配置文件

#  读取config.ini文件
cf.read(config.ini)

然后进行配置文件的读取操作。

以get为例,示例代码如下:

#  定义方法,获取config分组下指定name的值
def getConfigValue(self, name):
    value = self.cf.get("config", name)
    return value
#  定义方法,获取cmd分组下指定name的值
def getCmdValue(self, name):
    value = self.cf.get("cmd", name)
    return value

通过get(section, option)方法,可以获取指定分组下指定名称的值,其他方法类似,可参照着尝试。

基本的写入操作:

  • -write(fp)  将config对象写入至某个 .init 格式的文件  Write an .ini-format representation of the configuration state.
  • -add_section(section)   添加一个新的section
  • -set( section, option, value   对section中的option进行设置,需要调用write将内容写入配置文件
  • -remove_section(section)  删除某个 section
  • -remove_option(section, option) 

以set(section, option, value)为例,示例代码如下:

#  定义方法,修改config分组下指定name的值value
def setConfigValue(self, name, value):
    cfg = self.cf.set("config", name, value)
    fp = open(r'config.ini', 'w')
    cfg.write(fp)

其他方法可以自行尝试。

配置文件中的名字是不区分大小写的,如下两个是等价的:

#  不区分大小写,以下两个等价,都获取appActivity的值
self.cf.get("config", "appActivity")
self.cf.get("config", "APPACTIVITY")

在解析时,getboolean()方法查找任何可行的值,例如以下几个都是等价的:

#  以下取得的值都是等价的为ture
[log]
log_error=true
log_error=TRUE
log_error=1
log_error=yes

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们