Python如何使用ConfigParser讀取配置文件
在項目過程中,需要設(shè)置各種IP和端口號信息等,如果每次都在源程序中更改會很麻煩(因為每次都要重啟項目重新加載配置信息),因此將需要修改的參數(shù)寫在配置文件(或者數(shù)據(jù)庫)中,每次只需修改配置文件,就可以實現(xiàn)同樣的目的。Python 標準庫的 ConfigParser 模塊提供一套 API 來讀取和操作配置文件。因此在程序開始位置要導入該模塊,注意區(qū)分是python2還是python3,python3有一些改動
import ConfigParser #python 2.ximport configparser #python 3.x
配置文件的格式
a) 配置文件中包含一個或多個 section, 每個 section 有自己的 option; b) section 用 [sect_name] 表示,每個option是一個鍵值對,使用分隔符 = 或 : 隔開; c) 在 option 分隔符兩端的空格會被忽略掉 d) 配置文件使用 # 和 ; 注釋一個簡單的配置文件樣例 config.conf
# database source[db] # 對應(yīng)的是一個sectionhost = 127.0.0.1 # 對應(yīng)的是一個option鍵值對形式port = 3306user = rootpass = root # ssh[ssh]host = 192.168.10.111user = seanpass = sean
ConfigParser 的基本操作
a) 實例化 ConfigParser 并加載配置文件
cp = ConfigParser.SafeConfigParser()cp.read(’config.conf’)
b) 獲取 section 列表、option 鍵列表和 option 鍵值元組列表
print(’all sections:’, cp.sections()) # sections: [’db’, ’ssh’]print(’options of [db]:’, cp.options(’db’)) # options of [db]: [’host’, ’port’, ’user’, ’pass’]print(’items of [ssh]:’, cp.items(’ssh’)) # items of [ssh]: [(’host’, ’192.168.10.111’), (’user’, ’sean’), (’pass’, ’sean’)]
c) 讀取指定的配置信息
print(’host of db:’, cp.get(’db’, ’host’)) # host of db: 127.0.0.1print(’host of ssh:’, cp.get(’ssh’, ’host’)) # host of ssh: 192.168.10.111
d) 按類型讀取配置信息:getint、 getfloat 和 getboolean
print(type(cp.getint(’db’, ’port’))) # <type ’int’>
e) 判斷 option 是否存在
print(cp.has_option(’db’, ’host’)) # True
f) 設(shè)置 option
cp.set(’db’, ’host’,’192.168.10.222’)
g) 刪除 option
cp.remove_option(’db’, ’host’)
h) 判斷 section 是否存在
print(cp.has_section(’db’)) # True
i) 添加 section
cp.add_section(’new_sect’)
j) 刪除 section
cp.remove_section(’db’)
k) 保存配置,set、 remove_option、 add_section 和 remove_section 等操作并不會修改配置文件,write 方法可以將 ConfigParser 對象的配置寫到文件中
cp.write(open(’config.conf’, ’w’))cp.write(sys.stdout)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. vue實現(xiàn)web在線聊天功能2. JavaEE SpringMyBatis是什么? 它和Hibernate的區(qū)別及如何配置MyBatis3. JavaScript實現(xiàn)頁面動態(tài)驗證碼的實現(xiàn)示例4. Springboot 全局日期格式化處理的實現(xiàn)5. Java使用Tesseract-Ocr識別數(shù)字6. 完美解決vue 中多個echarts圖表自適應(yīng)的問題7. Python使用urlretrieve實現(xiàn)直接遠程下載圖片的示例代碼8. SpringBoot+TestNG單元測試的實現(xiàn)9. 在Chrome DevTools中調(diào)試JavaScript的實現(xiàn)10. 解決Android Studio 格式化 Format代碼快捷鍵問題
