python的配置文件這樣寫:
一、創(chuàng)建配置文件
在D盤建立一個(gè)配置文件,名字為:test.ini
內(nèi)容如下:
[baseconf]
host=127.0.0.1
port=3306
user=root
password=root
db_name=gloryroad
[test]
ip=127.0.0.1
int=1
float=1.5
bool=True
注意:要將文件保存為ansi編碼,utf-8編碼會(huì)報(bào)錯(cuò)
文件中的[baseconf]為section
二、讀配置文件
importConfigParser
cf=ConfigParser.ConfigParser()
cf.read(path)讀配置文件(ini、conf)返回結(jié)果是列表
cf.sections()獲取讀到的所有sections(域),返回列表類型
cf.options('sectionname')某個(gè)域下的所有key,返回列表類型
cf.items('sectionname')某個(gè)域下的所有key,value對(duì)
value=cf.get('sectionname','key')獲取某個(gè)yu下的key對(duì)應(yīng)的value值
cf.type(value)獲取的value值的類型
(1)getint(section,option)
獲取section中option的值,返回int類型數(shù)據(jù),所以該函數(shù)只能讀取int類型的值。
(2)getboolean(section,option)
獲取section中option的值,返回布爾類型數(shù)據(jù),所以該函數(shù)只能讀取boolean類型的值。
(3)getfloat(section,option)
獲取section中option的值,返回浮點(diǎn)類型數(shù)據(jù),所以該函數(shù)只能讀取浮點(diǎn)類型的值。
(4)has_option(section,option)
檢測(cè)指定section下是否存在指定的option,如果存在返回True,否則返回False。
(5)has_section(section)
檢測(cè)配置文件中是否存在指定的section,如果存在返回True,否則返回False。
三、動(dòng)態(tài)寫配置文件
cf.add_section('test')添加一個(gè)域
cf.set('test3','key12','value12')域下添加一個(gè)keyvalue對(duì)
cf.write(open(path,'w'))要使用'w'
learntofail,failuretolearn
以上內(nèi)容為大家介紹了python的配置文件怎樣寫?希望對(duì)大家有所幫助,如果想要了解更多Python相關(guān)知識(shí),請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。