詳解Python讀取配置文件模塊ConfigParser
1,ConfigParser模塊簡(jiǎn)介
假設(shè)有如下配置文件,需要在Pyhton程序中讀取
$ cat config.ini [db] db_port = 3306 db_user = root db_host = 127.0.0.1 db_pass = xgmtest [SectionOne] Status: Single Name: Derek Value: Yes Age: 30 Single: True [SectionTwo] FavoriteColor = Green [SectionThree] FamilyName: Johnson [Others] Route: 66
如何在Python中讀取呢
>>> import ConfigParser >>> Config = ConfigParser.ConfigParser() >>> Config <ConfigParser.ConfigParser instance at 0x00BA9B20> >>> Config.read("config.ini") ['config.ini'] >>> Config.sections() ['db', 'Others', 'SectionThree', 'SectionOne', 'SectionTwo'] >>> Config.get("db", "db_host") '127.0.0.1' >>> Config.getint("db", "db_port") 3306
2,ConfigParser模塊的基本方法介紹
讀取配置文件
read(filename) 直接讀取ini文件內(nèi)容 sections() 得到所有的section,并以列表的形式返回 options(section) 得到該section的所有option items(section) 得到該section的所有鍵值對(duì) get(section,option) 得到section中option的值,返回為string類型 getint(section,option) 得到section中option的值,返回為int類型,還有相應(yīng)的getboolean()和getfloat() 函數(shù)
寫入配置文件
add_section(section) 添加一個(gè)新的section set(section, option, value) 對(duì)section中的option進(jìn)行設(shè)置,需要調(diào)用write將內(nèi)容寫入配置文件
3,特殊情況
如果有以下配置文件
[zone1] 192.168.10.13 192.168.10.15 192.168.10.16 192.168.10.17 [zone2] 192.168.11.13 192.168.11.14 192.168.11.15 [zone3] 192.168.12.13 192.168.12.14 192.168.12.15
這種配置文件,每一個(gè)section里面,并不是健值對(duì)的形式,此時(shí)再調(diào)用ConfigParser讀取便會(huì)報(bào)出如下錯(cuò)誤:
ConfigParser.ParsingError: File contains parsing errors: hosts.txt
所以正確的調(diào)用方法為:
#!/usr/bin/python import ConfigParser config = ConfigParser.ConfigParser(allow_no_value=True) config.read("hosts.txt") print config.items("zone2")
運(yùn)行結(jié)果:
$ ./a.py [('10.189.22.21', None), ('10.189.22.22', None), ('10.189.22.23', None)]
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python單線程文件傳輸?shù)膶?shí)例(C/S)
今天小編就為大家分享一篇python單線程文件傳輸?shù)膶?shí)例(C/S),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2019-02-02解決pycharm運(yùn)行出錯(cuò),代碼正確結(jié)果不顯示的問題
今天小編就為大家分享一篇解決pycharm運(yùn)行出錯(cuò),代碼正確結(jié)果不顯示的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2018-11-11python-tkinter之按鈕的使用,開關(guān)方法
今天小編就為大家分享一篇python-tkinter之按鈕的使用,開關(guān)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2019-06-06Python設(shè)計(jì)模式結(jié)構(gòu)型代理模式
這篇文章主要介紹了Python設(shè)計(jì)模式結(jié)構(gòu)型代理模式,代理模式即Proxy?Pattern,為其他對(duì)象提供一種代理以控制對(duì)這個(gè)對(duì)象的訪問,下文內(nèi)容詳細(xì)介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-02-02Pyspark獲取并處理RDD數(shù)據(jù)代碼實(shí)例
這篇文章主要介紹了Pyspark獲取并處理RDD數(shù)據(jù)代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03python opencv捕獲攝像頭并顯示內(nèi)容的實(shí)現(xiàn)
這篇文章主要介紹了python opencv捕獲攝像頭并顯示內(nèi)容的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07