如何寫(xiě)python的配置文件
一、創(chuàng)建配置文件
在D盤(pán)建立一個(gè)配置文件,名字為:test.ini
內(nèi)容如下:
[baseconf]host=127.0.0.1port=3306user=rootpassword=rootdb_name=gloryroad[test]ip=127.0.0.1int=1float=1.5bool=True
注意:要將文件保存為ansi編碼,utf-8編碼會(huì)報(bào)錯(cuò)
文件中的[baseconf]為section
二、讀配置文件
import ConfigParser
cf=ConfigParser.ConfigParser()
cf.read(path) 讀配置文件(ini、conf)返回結(jié)果是列表
cf.sections() 獲取讀到的所有sections(域),返回列表類(lèi)型
cf.options(’sectionname’) 某個(gè)域下的所有key,返回列表類(lèi)型
cf.items(’sectionname’) 某個(gè)域下的所有key,value對(duì)
value=cf.get(’sectionname’,’key’) 獲取某個(gè)yu下的key對(duì)應(yīng)的value值
cf.type(value) 獲取的value值的類(lèi)型
(1)getint(section, option)
獲取section中option的值,返回int類(lèi)型數(shù)據(jù),所以該函數(shù)只能讀取int類(lèi)型的值。
(2)getboolean(section, option)
獲取section中option的值,返回布爾類(lèi)型數(shù)據(jù),所以該函數(shù)只能讀取boolean類(lèi)型的值。
(3)getfloat(section, option)
獲取section中option的值,返回浮點(diǎn)類(lèi)型數(shù)據(jù),所以該函數(shù)只能讀取浮點(diǎn)類(lèi)型的值。
(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
內(nèi)容擴(kuò)展:
python使用配置文件過(guò)程
通過(guò)配置文件將變量暴露給用戶修改
標(biāo)準(zhǔn)庫(kù)模塊configparser,從而可在配置文件中使用標(biāo)準(zhǔn)格式。
必須使用[files]、[colors]等標(biāo)題將配置文件分成幾部分(section)。標(biāo)題的名稱可隨便指定,但必須將它們用方括號(hào)括起。
$ cat area.ini[numbers]pi: 3.1415926535893971[messages]greeting: Welcome to the area calutation program!question: plse enter the radiusresult_message: The area is
使用python 讀取他
from configparser import ConfigParserCONFIGFILE = 'area.ini'config = ConfigParser()#讀取配置文件config.read(CONFIGFILE)print(config[’messages’].get(’greeting’))radius = float(input(config[’messages’].get(’question’) + ’ ’))# 以空格結(jié)束以便接著在當(dāng)前行打印:print(config[’messages’].get(’result_message’),end=’ ’)print(config[’numbers’].getfloat(’pi’) * radius**2)
到此這篇關(guān)于如何寫(xiě)python的配置文件的文章就介紹到這了,更多相關(guān)python寫(xiě)配置文件方法內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python爬蟲(chóng)實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊2. Spring如何使用xml創(chuàng)建bean對(duì)象3. Android Studio設(shè)置顏色拾色器工具Color Picker教程4. python 利用toapi庫(kù)自動(dòng)生成api5. python實(shí)現(xiàn)PolynomialFeatures多項(xiàng)式的方法6. HTML 絕對(duì)路徑與相對(duì)路徑概念詳細(xì)7. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法8. Java程序的編碼規(guī)范(6)9. python實(shí)現(xiàn)在內(nèi)存中讀寫(xiě)str和二進(jìn)制數(shù)據(jù)代碼10. python實(shí)現(xiàn)讀取類(lèi)別頻數(shù)數(shù)據(jù)畫(huà)水平條形圖案例
