ConfigParser 读写配置文件

一、ini:

1..ini 文件是Initialization File的缩写,即初始化文件,是windows的系统配置文件所采用的存储格式

2.ini文件创建方法:

(1)先建立一个记事本文件。
(2)工具 - 文件夹选项 - 查看 - 去掉“隐藏已知文件的扩展名”前面的√。这样一来,你建立的那个记事本的扩展名就显示出来了“*.txt”。然后,你把这个.txt扩展名更改为.ini

3.ini文件的格式:

  (1)节:section

    节用方括号括起来,单独占一行,例如:
    [section]
  (2)键:key
    键(key)又名属性(property),单独占一行用等号连接键名和键值,例如:
    name=value
  (3)注释:comment
    注释使用英文分号(;)开头,单独占一行。在分号后面的文字,直到该行结尾都全部为注释,例如:
    ; comment text
 
二、ConfigParser

读写配置文件ConfigParser模块是python自带的读取配置文件的模块.通过他可以方便的读取配置文件。

Python的ConfigParser Module中定义了3个类对INI文件进行操作。分别是RawConfigParser、ConfigParser、SafeConfigParser。RawCnfigParser是最基础的INI文件读取类,ConfigParser、SafeConfigParser支持对%(value)s变量的解析。

1.读取配置文件

  -read(filename)   直接读取ini文件内容
  -sections()   得到所有的section,并以列表的形式返回
  -options(section)   得到该section的所有option(选项)
  -items(section)   得到该section的所有键值对
  -get(section,option)   得到section中option的值,返回为string类型
  -getint(section,option)   得到section中option的值,返回为int类型

2.写入配置文件

-add_section(section)   添加一个新的section

-set( section, option, value)   对section中的option进行设置

-remove_section(section)                             删除某个 section

-remove_option(section, option)                 删除某个 section 下的 option


  需要调用write将内容写回到配置文件。

3.测试代码

(1)配置文件test.cfg

  [sec_a]  

  a_key1 = 20  

  a_key2 = 10  

  [sec_b]  

  b_key1 = 121  

  b_key2 = b_value2  

  b_key3 = $r  

  b_key4 = 127.0.0.1  

(2)测试文件(test.py):

  #生成config对象  

  conf = ConfigParser.ConfigParser()  

  #用config对象读取配置文件  

  conf.read("test.cfg")  

  #以列表形式返回所有的section  

  sections = conf.sections()  

    print 'sections:', sections         #sections: ['sec_b', 'sec_a']  

  #得到指定section的所有option  

  options = conf.options("sec_a")  

    print 'options:', options           #options: ['a_key1', 'a_key2']  

  #得到指定section的所有键值对  

  kvs = conf.items("sec_a")    

    print 'sec_a:', kvs                 #sec_a: [('a_key1', '20'), ('a_key2', '10')]  

  #指定section,option读取值  

  str_val = conf.get("sec_a", "a_key1")  

  int_val = conf.getint("sec_a", "a_key2")  

    print "value for sec_a's a_key1:", str_val       #value for sec_a's a_key1: 20  

    print "value for sec_a's a_key2:", int_val       #value for sec_a's a_key2: 10  

  #写配置文件  

  #更新指定section,option的值  

  conf.set("sec_b", "b_key3", "new-$r")  

  #写入指定section增加新option和值  

  conf.set("sec_b", "b_newkey", "new-value")  

  #增加新的section  

  conf.add_section('a_new_section')  

  conf.set('a_new_section', 'new_key', 'new_value')  

  #写回配置文件  

  conf.write(open("test.cfg", "w"))  

原文地址:https://www.cnblogs.com/linbao/p/8323610.html