標籤:地區 pre 有一個 forward .com [] 常用模組 add 列印
python常用模組之configparser
作用:解析設定檔
假設在目前的目錄下有這樣一個conf.ini檔案
[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes[bitbucket.org]User = hg[topsecret.server.com]Port = 50022ForwardX11 = no
模組的操作
import configparserconf = configparser.ConfigParser() # 建立一個對象# print(conf.sections()) # [],因為沒有開啟檔案,所以是空的conf.read("conf.ini") # 讀取檔案內容print(conf.sections()) # [‘bitbucket.org‘, ‘topsecret.server.com‘]# 那麼為什麼沒有DEFAULT呢?因為在每一個設定檔中都會有一個DEFAULT,這是全域預設配置的東西,列印不出來的,但是可以擷取到print(conf.default_section) # DEFAULT# 拿到裡面的值print(conf[‘bitbucket.org‘][‘User‘]) # hg 此時是知道這個設定檔中的子模組bitbucket.org裡有User# 迴圈for k,v in conf[‘bitbucket.org‘].items(): print(k,v)# user hg# serveraliveinterval 45# compression yes# compressionlevel 9# forwardx11 yes那麼,為啥會把DEFAULT裡的列印出來呢?因為這是configparser設定的,會預設出現在每一個節點中
configparser其他的操作
# 還是以上面的conf.ini為例import configparserconf = configparser.ConfigParser() # 產生一個對象conf.read("conf.ini",encoding=‘utf-8‘) # 讀取設定檔內容# 讀# print(dir(conf))print(conf.options("bitbucket.org")) # 將bitbucket.org地區裡的key全部拿出,包括DEFAULT裡面的,[‘user‘, ‘serveraliveinterval‘, ‘compression‘, ‘compressionlevel‘, ‘forwardx11‘]print(conf[‘bitbucket.org‘][‘User‘]) # hg,拿到bitbucket.org裡的User這個key的值# 增加conf.add_section("group1") # 增加name地區conf[‘group1‘][‘age‘] = ‘22‘ # 增加group1地區中age這個key的值為22conf[‘group1‘][‘name‘] = ‘xiao‘conf.write(open("conf.ini","r+")) # 寫進檔案中conf.write(open("i.cfg","w")) # 或者寫到一個新檔案中# 刪除# conf.remove_section(‘group1‘) # 刪除整個group1地區# conf.write(open(‘i.cfg‘,‘w‘))conf.remove_option(‘group1‘,‘name‘) # 只刪除group1地區裡的name這個keyconf.write(open(‘conf.ini‘,‘w‘))
python常用模組之configparser模組