1. 介紹
此模塊實現(xiàn)一種基本配置語言 ConfigParser
類结闸,這種語言所提供的結構與 Microsoft Windows INI 文件的類似,并不能夠解析或?qū)懭朐?Windows Registry 擴展版本 INI 語法中所使用的值-類型前綴捂人。
2. 配置文件形式
總的來說医清,這種文件由多個節(jié)組成,每個節(jié)包含多個帶有值的鍵哨查。configparser
類可以讀取和寫入這種文件回俐。
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
3. 寫入
import configparser
cf = configparser.ConfigParser()
cf["DEFAULT"] = {"ServerAliveInterval":"45","Compression":"yes"}
cf["bitbucket.org"]["User"] = "hg"
with open("d:\\config.ini") as f:
cf.write(f)
4. 讀取
import configparser
cf = configparser.ConfigParser()
print(cf.sessions()) # 結果是[]
cf.read("d:\\config.ini")
print(cf.sessions()) # 結果是['bitbucket.org', 'topsecret.server.com']
# 注意:沒有DEFAULT
for key in cf["bitbucket.org"]:
print(key) # 注意:DEFAULT的key也會顯示出來
cf["bitbucket.org"]["Compression"] = "yes"
- 注意:
DEFAULT
小節(jié)為所有其他小節(jié)提供了默認值 吹艇,小節(jié)中的鍵大小寫不敏感并且會存儲為小寫形式
5. 更新
cf = configparser.ConfigParser()
cf.read("d:\\config.ini")
cf.add_section("yuan")
cf.remove_section("bitbucket.org")
cf.remove_option("topsecret.server.com","forwardx11")
cf.set("yuan","k2","22222")
with open("d:\\config.ini","w") as f:
cf.write(f)
6. 支持的數(shù)據(jù)類型
配置解析器不會猜測配置文件中值的類型麦牺,而是將它們存儲為字符串钮蛛。 這意味著如果需要其他數(shù)據(jù)類型,應當自行來轉(zhuǎn)換:
>>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0
由于經(jīng)常需要這樣操作剖膳,配置解析器提供了一系列獲取方法來處理整數(shù)魏颓、浮點數(shù)和布爾值的方法。 最后一個類型的處理最為有趣吱晒,因為簡單地將值傳給 bool()
是沒有用的甸饱,bool('False')
仍然會是 True
。 為解決這個問題配置解析器提供了 getboolean()
仑濒。 這個方法對大小寫不敏感并可識別 'yes'
/'no'
, 'on'
/'off'
, 'true'
/'false'
和 '1'
/'0'
等布爾值柜候。 例如:
>>> topsecret.getboolean('ForwardX11')
False
>>> config['bitbucket.org'].getboolean('ForwardX11')
True
>>> config.getboolean('bitbucket.org', 'Compression')
True
除了 getboolean()
,配置解析器還提供了同類的 getint()
和 getfloat()
方法躏精。