python常用模組之configparser模組

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.