python解析設定檔---configparser模組

來源:互聯網
上載者:User

標籤:類型   檔案格式   admin   user   .config   igp   conf   res   取值   

1.configparser模組介紹

configparser是用來讀取設定檔的模組,設定檔格式為:中括弧“[ ]”內包含的為section。section 下面為類似於key-value 的配置內容。

 

a.conf的檔案內容如下:

[user01]name = user01is_admin = Trueage = 34passwd = user123456[yxwang]name = yxwangage = 25passwd = 123456

取值:

import configparser#取值config=configparser.ConfigParser()  #調用condigparser下的ConfigParser的方法,得到一個對象config.read(‘a.conf‘)  #寫上設定檔的路徑,開啟檔案.print(config.sections())  #得到設定檔中的標題。  #[‘user01‘, ‘yxwang‘]print(config.options(config.sections()[0])) #查看某個標題下的配置項 等同於擷取user01下的配置項的keyres=config.get(‘user01‘,‘passwd‘)#查看某個標題下的某個配置項的值  注意這樣得到的數值是字串類型res1=config.getint(‘user01‘,‘age‘) #這樣得到的數值是一個字串.res1=config.getboolean(‘user01‘,‘is_admin‘) #這樣得到的數值是一個布爾值.print(res)

修改:

import configparserconfig=configparser.ConfigParser()  #調用condigparser下的ConfigParser的方法,得到一個對象config.read(‘a.conf‘)  #寫上設定檔的路徑,開啟檔案.config.remove_section(‘yxwang‘)  #刪除一個標題,標題刪除了標題下的內容也一併刪除了config.remove_option(‘user01‘,‘age‘) #刪除一個標題下的內容config.add_section(‘user03‘)  #新增一個標題config.set(‘user03‘,‘name‘,‘user03‘)  #為指定標題插入內容config.write(open(‘a.conf‘,‘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.