python学习笔记之读取配置文件

1.配置一个.int文件用来写配置文件,例如

#  定义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

2.基本的读操作

  • -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)

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

#  定义方法,获取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

基本的写入操作:

  • -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) 
#  定义方法,修改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")

 

posted @ 2021-07-12 21:55  albert11  阅读(795)  评论(0编辑  收藏  举报