天天看點

Python ConfigParser的使用

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将内容寫入配置檔案。

3.Python的ConfigParser

Module中定義了3個類對INI檔案進行操作。

分别是RawConfigParser、ConfigParser、

SafeConfigParser。

RawCnfigParser是最基礎的INI檔案讀取類;

ConfigParser、

SafeConfigParser支援對%(value)s變量的解析。 

設定配置檔案test.conf

[portal] 

url = http://%(host)s:%(port)s/Portal 

host = localhost 

port = 8080 

使用RawConfigParser:

import ConfigParser 

file1 = ConfigParser.RawConfigParser()

file1.read('aa.txt')

print(file1.get('portal','url'))

得到終端輸出:

http://%(host)s:%(port)s/Portal

使用ConfigParser:

file2 = ConfigParser.ConfigParser()

file2.read('aa.txt')

print(file2.get('portal','url'))

http://localhost:8080/Portal

使用SafeConfigParser:

cf = ConfigParser.SafeConfigParser() 

file3 = ConfigParser.SafeConfigParser()

file3.read('aa.txt')

print(file3.get('portal','url'))

得到終端輸出(效果同ConfigParser):