Python如何使用ConfigParser讀取配置文件
在項(xiàng)目過程中,需要設(shè)置各種IP和端口號信息等,如果每次都在源程序中更改會(huì)很麻煩(因?yàn)槊看味家貑㈨?xiàng)目重新加載配置信息),因此將需要修改的參數(shù)寫在配置文件(或者數(shù)據(jù)庫)中,每次只需修改配置文件,就可以實(shí)現(xiàn)同樣的目的。Python 標(biāo)準(zhǔn)庫的 ConfigParser 模塊提供一套 API 來讀取和操作配置文件。因此在程序開始位置要導(dǎo)入該模塊,注意區(qū)分是python2還是python3,python3有一些改動(dòng)
import ConfigParser #python 2.ximport configparser #python 3.x
配置文件的格式
a) 配置文件中包含一個(gè)或多個(gè) section, 每個(gè) section 有自己的 option; b) section 用 [sect_name] 表示,每個(gè)option是一個(gè)鍵值對,使用分隔符 = 或 : 隔開; c) 在 option 分隔符兩端的空格會(huì)被忽略掉 d) 配置文件使用 # 和 ; 注釋一個(gè)簡單的配置文件樣例 config.conf
# database source[db] # 對應(yīng)的是一個(gè)sectionhost = 127.0.0.1 # 對應(yīng)的是一個(gè)option鍵值對形式port = 3306user = rootpass = root # ssh[ssh]host = 192.168.10.111user = seanpass = sean
ConfigParser 的基本操作
a) 實(shí)例化 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 等操作并不會(huì)修改配置文件,write 方法可以將 ConfigParser 對象的配置寫到文件中
cp.write(open(’config.conf’, ’w’))cp.write(sys.stdout)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. IntelliJ IDEA導(dǎo)入jar包的方法2. js實(shí)現(xiàn)貪吃蛇小游戲(加墻)3. 基于Go和PHP語言實(shí)現(xiàn)爬樓梯算法的思路詳解4. JAMon(Java Application Monitor)備忘記5. JVM之class文件結(jié)構(gòu)6. Html5播放器實(shí)現(xiàn)倍速播放的方法示例7. asp知識整理筆記4(問答模式)8. Python中Anaconda3 安裝gdal庫的方法9. JSP實(shí)現(xiàn)百萬富翁猜數(shù)字游戲10. python對批量WAV音頻進(jìn)行等長分割的方法實(shí)現(xiàn)
