1. 程式人生 > >ConfigParser 讀寫配置文件

ConfigParser 讀寫配置文件

raw 讀寫 bsp gpa span remove 得到 windows option

一、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"))

ConfigParser 讀寫配置文件