標籤:new rem conf 指定 use div ons 設定檔 pytho
一、configparser模組的作用
configparser適用於產生並操作如下格式的設定檔
[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes [bitbucket.org]User = hg [topsecret.server.com]Port = 50022ForwardX11 = no
二、如何用configparser模組產生如上格式的設定檔
匯入configparser模組後,產生一個configparser的對象,然後像字典的方式定義設定檔的內容,最後開啟一個檔案將定義的內容寫入檔案即可,比如
import configparserconfig=configparser.ConfigParser() #產生對象config["DEFAULT"]={ ‘ServerAliveInterval‘: ‘45‘, ‘Compression‘: ‘yes‘, ‘CompressionLevel‘: ‘9‘, ‘ForwardX11‘:‘yes‘}config["bitbucket.org"]={‘User‘:‘hg‘} #組建組態檔案的內容config[‘topsecret.server.com‘]={‘Host Port‘:‘50022‘,‘ForwardX11‘:‘no‘}with open(‘example.ini‘,‘w‘) as configfile: config.write(configfile) #將配置寫入檔案
三、從設定檔中擷取資訊
import configparserconfig=configparser.ConfigParser()config.read(‘example.ini‘) #讀入設定檔print(config.sections()) #輸出所有節點名稱print(‘bytebong.com‘ in config)print(‘bitbucket.org‘ in config) #判斷指定節點是否存在print(config[‘bitbucket.org‘]["user"]) #取值print(config[‘bitbucket.org‘]) #輸出節點名稱for key in config[‘bitbucket.org‘]: #輸出節點中每個配置項的名字,如果有DEFAULT則會將DEFAULT的配置項也一起輸出 print(key)print(config.options(‘bitbucket.org‘))#作用同上面的for,結果為列表print(config.items(‘bitbucket.org‘))#輸出為列表,元素是每個配置項何其參數的元祖,同樣會輸出DEFAULT的配置print(config.get(‘bitbucket.org‘,‘user‘))#擷取指定節點中指定配置項的參數,同樣可以擷取DEFAULT中的配置項參數
四、增刪改
import configparser
config = configparser.ConfigParser()
config.read(‘example.ini‘)
config.add_section(‘yuan‘) #建立新節點
config.remove_section(‘bitbucket.org‘) #刪除節點
config.remove_option(‘topsecret.server.com‘,"forwardx11") #刪除配置項
config.set(‘topsecret.server.com‘,‘k1‘,‘11111‘) #增加配置項
config.set(‘yuan‘,‘k2‘,‘22222‘)
config.write(open(‘new2.ini‘, "w")) #將修改後的配置寫入檔案
python常用模組之configparser模組