Python如何使用ConfigParser讀取配置文件
在項目過程中,需要設(shè)置各種IP和端口號信息等,如果每次都在源程序中更改會很麻煩(因為每次都要重啟項目重新加載配置信息),因此將需要修改的參數(shù)寫在配置文件(或者數(shù)據(jù)庫)中,每次只需修改配置文件,就可以實現(xiàn)同樣的目的。Python 標(biāo)準(zhǔn)庫的 ConfigParser 模塊提供一套 API 來讀取和操作配置文件。因此在程序開始位置要導(dǎo)入該模塊,注意區(qū)分是python2還是python3,python3有一些改動
import ConfigParser #python 2.x
import configparser #python 3.x
配置文件的格式
- a) 配置文件中包含一個或多個 section, 每個 section 有自己的 option;
- b) section 用 [sect_name] 表示,每個option是一個鍵值對,使用分隔符 = 或 : 隔開;
- c) 在 option 分隔符兩端的空格會被忽略掉
- d) 配置文件使用 # 和 ; 注釋
一個簡單的配置文件樣例 config.conf
# database source [db] # 對應(yīng)的是一個section host = 127.0.0.1 # 對應(yīng)的是一個option鍵值對形式 port = 3306 user = root pass = root # ssh [ssh] host = 192.168.10.111 user = sean pass = 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.1
print('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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python機器學(xué)習(xí)庫scikit-learn安裝與基本使用教程
這篇文章主要介紹了Python機器學(xué)習(xí)庫scikit-learn安裝與基本使用,較為詳細(xì)的介紹了機器學(xué)習(xí)庫scikit-learn的功能、原理、基本安裝與簡單使用方法,需要的朋友可以參考下2018-06-06Python過濾函數(shù)filter()使用自定義函數(shù)過濾序列實例
這篇文章主要介紹了Python過濾函數(shù)filter()使用自定義函數(shù)過濾序列實例,配合自定義函數(shù)可以實現(xiàn)許多強大的功能,需要的朋友可以參考下2014-08-08對TensorFlow中的variables_to_restore函數(shù)詳解
今天小編就為大家分享一篇對TensorFlow中的variables_to_restore函數(shù)詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07