python ConfigParser 参数化配置 学习笔记

╰+哭是因爲堅強的太久メ 2022-08-21 00:08 197阅读 0赞

python中ConfigParser 是用来读取配置文件的模块,可读写ini、cfg、conf等后缀的配置文件

  1. rconf.ini
  2. [auther]
  3. ;sections
  4. name = johnny
  5. ;options key = value
  6. gender = male
  7. age = 24
  8. [information]
  9. blogaddress = blog.csdn.net/z_johnny

read_write.py

  1. #coding:utf-8
  2. import ConfigParser
  3. def read(rConfFileName):
  4. init = ConfigParser.ConfigParser() # 初始化实例
  5. init.read("%s"%rConfFileName) # 读取配置文件
  6. sections = init.sections() # 获取所有sections
  7. print "sections : ",sections # 输出列表
  8. options = init.options("auther") # 获取指定section 的options
  9. print "options : ",options # 输出列表,指定section里的所有key
  10. items = init.items("information") # 获取指定section 的配置信息
  11. print "items : ",items
  12. information_blogaddress = init.get("information", "blogaddress") # 读取指定section中指定option 信息,type为str
  13. print "information_blogaddress : ",information_blogaddress
  14. auther_age = init.getint("auther", "age") #获取的option为整型
  15. print "auther_age : ",auther_age
  16. def write(wConfFileName):
  17. init = ConfigParser.ConfigParser() # 初始化实例
  18. init.add_section('time') # 添加一个section
  19. init.set("time", "today", "sunday") # 设置某个option 的值
  20. init.write(open("%s"%wConfFileName, "w")) # 写入“w”,追加“a”
  21. init.add_section('times') # 添加一个要删除的section
  22. init.set("times", "tomorrowss", "mondays") # 该项后面要删除
  23. init.remove_option('times','tomorrowss') # 移除option,打开文件看一下,在把下面的注释(#)去掉
  24. #init.remove_section('times') # 移除section
  25. init.write(open("%s"%wConfFileName, "w")) # 写入“w”,追加“a”
  26. if __name__ == "__main__":
  27. read('rconf.ini')
  28. write('wconf.ini') # 自动创建wconf.ini

read输出:

  1. sections : ['auther', 'information']
  2. options : ['name', 'gender', 'age']
  3. items : [('blogaddress', 'blog.csdn.net/z_johnny')]
  4. information_blogaddress : blog.csdn.net/z_johnny
  5. auther_age : 24

wirte输出文件wconf.ini

  1. [time]
  2. today = sunday

读取指定section中指定option 信息,获取到的内容type为str,如需转换成list,请看下面

  1. ReadMe.ini
  2. [reader]
  3. qqqqqq = 15,26,30

``

  1. #!/usr/bin/env python
  2. #coding:utf-8
  3. #2018/01/25 create by johnny
  4. import ConfigParser
  5. strChange = ConfigParser.ConfigParser()
  6. strChange.read("C:\Users\Jim\Desktop\ReadMe.ini")
  7. getstr = strChange.get("reader","qqqqqq")
  8. strChangelist_eval = eval(getstr)
  9. print strChangelist_eval,type(strChangelist_eval),strChangelist_eval[1],type(strChangelist_eval[1])

发表评论

表情:
评论列表 (有 0 条评论,197人围观)

还没有评论,来说两句吧...

相关阅读