1. 程式人生 > >Python操作配置資訊的工具類ConfigParser的使用講解

Python操作配置資訊的工具類ConfigParser的使用講解

.ini 檔案是Initialization File的縮寫,即初始化檔案 ,是windows的系統配置檔案所採用的儲存格式,統管windows的各項配置,一般使用者就用windows提供的各項圖形化管理介面就可實現相同的配置了。但在某些情況,還是要直接編輯.ini才方便,一般只有很熟悉windows才能去直接編輯。開始時用於WIN3X下面,WIN95用登錄檔代替,以及後面的內容表示一個節,相當於登錄檔中的鍵。
除了windows2003很多其他作業系統下面的應用軟體也有.ini檔案,用來配置應用軟體以實現不同使用者的要求。一般不用直接編輯這些.ini檔案,應用程式的圖形介面即可操作以實現相同的功能。它可以用來存放軟體資訊,登錄檔資訊等。
1.基本的讀取配置檔案
1)直接讀取ini檔案內容
import ConfigParser

config = ConfigParser.RawConfigParser(allow_no_value=True)
config.read('test.ini')
print config
#<ConfigParser.RawConfigParser instance at 0x0240F9B8>
2)得到所有的section,並以list列表的形式返回
print config.sections()
#['login_account_info']
3)得到該section的所有option,並以list列表的形式返回
sects = config.sections()
for
row in sects: print config.options(row) #['login_username', 'login_uid', 'login_password', 'cookies_file']
4)得到該section的所有鍵值對,返回的資料是tupple的list集合
sects = config.sections()
for row in sects:
    # print config.options(row)
    print config.items(row)
#[('login_username', 'ur_weibo_account_id_here'
), ('login_uid', '1248521225'), ('login_password', 'ur_weibo_account_password_here'), ('cookies_file', 'weibo_cookies.dat')]
5)get(section,option)得到section中option的值,返回為string型別
print config.get('login_account_info', 'cookies_file')
6)getint(section,option) 得到section中option的值,返回為int型別,還有相應的getboolean()和getfloat() 
print config.getint('login_account_info','test_int')
2.基本的寫入配置檔案
1)add_section(section) 新增一個新的section
2)set( section, option, value) 對section中的option進行設定,需要呼叫write將內容寫入配置檔案。
config.add_section('cainiao')
config.set('cainiao', 'test_float', '23.67')
config.set('cainiao', 'test_float', '23.67123')
config.write(open('test1.ini', 'w+'))

輸出的結果是

[cainiao]
test_float = 23.67123
還請大神多多指導