新聞中心
一、創(chuàng)建配置文件

成都創(chuàng)新互聯(lián)公司是一家專注于做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)與策劃設(shè)計(jì),慈溪網(wǎng)站建設(shè)哪家好?成都創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)10多年,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:慈溪等地區(qū)。慈溪做網(wǎng)站價(jià)格咨詢:028-86922220
在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
二、讀配置文件
import ConfigParser
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)寫(xiě)配置文件
cf.add_section('test') 添加一個(gè)域
cf.set('test3','key12','value12') 域下添加一個(gè)key value對(duì)
cf.write(open(path,'w')) 要使用'w'
learn to fail, failure to learn
分享題目:創(chuàng)新互聯(lián)Python教程:python的配置文件怎樣寫(xiě)?
標(biāo)題URL:http://fisionsoft.com.cn/article/cdheeoj.html


咨詢
建站咨詢
