python常用模組之configparser模組

來源:互聯網
上載者:User

標籤: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模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.