Python ConfigParser的使用
1.基本的讀取配置文件
-read(filename) 直接讀取ini文件內(nèi)容
-sections() 得到所有的section,并以列表的形式返回
-options(section) 得到該section的所有option
-items(section) 得到該section的所有鍵值對(duì)
-get(section,option) 得到section中option的值,返回為string類(lèi)型
-getint(section,option) 得到section中option的值,返回為int類(lèi)型,還有相應(yīng)的getboolean()和getfloat() 函數(shù)。
?
2.基本的寫(xiě)入配置文件
-add_section(section) 添加一個(gè)新的section
-set( section, option, value) 對(duì)section中的option進(jìn)行設(shè)置,需要調(diào)用write將內(nèi)容寫(xiě)入配置文件。
?
3.基本例子
test.conf
parse_test_conf.py
?
得到終端輸出:
sections: ['sec_b', 'sec_a']?
options: ['a_key1', 'a_key2']?
sec_a: [('a_key1', "i'm value"), ('a_key2', '22')]?
value for sec_a's a_key1: i'm value?
value for sec_a's a_key2: 22?
更新后的test.conf
4.Python的ConfigParser Module中定義了3個(gè)類(lèi)對(duì)INI文件進(jìn)行操作。分別是RawConfigParser、ConfigParser、SafeConfigParser。RawCnfigParser是最基礎(chǔ)的INI文件讀取類(lèi),ConfigParser、SafeConfigParser支持對(duì)%(value)s變量的解析。?
?
設(shè)定配置文件test2.conf
使用RawConfigParser:
得到終端輸出:
use RawConfigParser() read?
http://%(host)s:%(port)s/Portal?
use RawConfigParser() write?
%(host)s:%(port)s
改用ConfigParser:
得到終端輸出:
use ConfigParser() read?
http://localhost:8080/Portal?
use ConfigParser() write?
localhost:8080
改用SafeConfigParser:
得到終端輸出(效果同ConfigParser):
use SafeConfigParser() read?
http://localhost:8080/Portal?
use SateConfigParser() write?
localhost:8080?
轉(zhuǎn)載于:https://www.cnblogs.com/iplus/archive/2013/03/29/4489943.html
總結(jié)
以上是生活随笔為你收集整理的Python ConfigParser的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 使用RMAN备份控制文件(control
- 下一篇: websocket python爬虫_p