Python中設定檔解析模組-ConfigParser

來源:互聯網
上載者:User

標籤:sha   節點   obj   .com   write   包含   常用方法   檔案中   value   

Python中有ConfigParser類,可以很方便的從設定檔中讀取資料(如DB的配置,路徑的配置)。
設定檔的格式是: []包含的叫section, section 下有option=value這樣的索引值
該模組的常用方法
1、config=ConfigParser.ConfigParser()
建立ConfigParser執行個體
2、config.sections()
返回設定檔中節序列
3、config.options(section)
返回某個項目中的所有鍵的序列
4、config.get(section,option)
返回section節中,option的索引值
5、config.add_section(str)
添加一個設定檔節點(str)
6、config.set(section,option,val)
設定section節點中,鍵名為option的值(val)
7、config.read(filename)
讀取設定檔
8、config.write(obj_file)
寫入設定檔

例如:設定檔 test.conf [section1]name = tankage = 28[section2]ip = 192.168.1.1port = 8080程式碼範例:# -* - coding: UTF-8 -* - import ConfigParserconf = ConfigParser.ConfigParser()------建立一個對象conf.read("c:\\test.conf")# 擷取指定的section, 指定的option的值name = conf.get("section1", "name")print(name)age = conf.get("section1", "age")print age#擷取所有的section-----以數組形式輸出sections = conf.sections()print sections#寫設定檔# 更新指定section, option的值conf.set("section2", "port", "8081")# 寫入指定section, 增加新option的值conf.set("section2", "IEPort", "80")# 添加新的 sectionconf.add_section("new_section")conf.set("new_section", "new_option", "http://www.cnblogs.com/tankxiao")# 寫回設定檔conf.write(open("c:\\test.conf","w"))-------記住對設定檔的修改,最後一定要通過write方法寫入到設定檔中,否則無效

  

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.