1. 程式人生 > >python讀conf配置檔案--ConfigParser

python讀conf配置檔案--ConfigParser

python讀寫配置檔案還是比較方便得。
 
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型別,還有相應的getboolean()和getfloat() 函式。
 
2) 基本的寫入配置檔案
     -add_section(section) 新增一個新的section

     -set( section, option, value) 對section中的option進行設定,需要呼叫write將內容寫入配置檔案。

配置檔案如下:

[section1]
name = jhao
sex = mall

[section2]
ip = 192.168.1.1
port = 8888

工程路徑如下:

程式碼如下:


 
import ConfigParser
import os

conf = ConfigParser.ConfigParser()
# 讀取目錄E:\newWorkSpace\HATP\test_case
path = os.getcwd()
# 返回目錄E:\newWorkSpace\HATP
path = os.path.dirname(path)
path = path+'\conf1.ini'
# conf.read('E:/newWorkSpace/HATP/conf1.ini')
conf.read(path)

secs = conf.sections()
print secs
# 輸出['section1', 'section2']

sec = conf.options('section1')
print sec
# 輸出['name', 'sex']

it = conf.items('section1')
print it
# 輸出[('name', 'jhao'), ('sex', 'mall')]

#read by type
name = conf.get('section1','name')
print name
# 輸出 jhao
ip = conf.get('section2','ip')
print ip
# 輸出  192.168.1.1

#read by int
port = conf.getint('section2','port')
print port
# 輸出  8888

#modify one value and write to file
conf.set('section2','port',9999)
conf.write(open(path,"w"))


 
 
 
 3) Python的ConfigParser Module 中定義了3個類對INI檔案進行操作。分別是RawConfigParser、ConfigParser、SafeConfigParser。 RawCnfigParser是最基礎的INI檔案讀取類,ConfigParser、SafeConfigParser支援對%(value)s變數的 解析。