您的位置:首頁技術文章
文章詳情頁

Python如何使用ConfigParser讀取配置文件

瀏覽:4日期:2022-07-05 17:06:11

在項目過程中,需要設置各種IP和端口號信息等,如果每次都在源程序中更改會很麻煩(因為每次都要重啟項目重新加載配置信息),因此將需要修改的參數寫在配置文件(或者數據庫)中,每次只需修改配置文件,就可以實現同樣的目的。Python 標準庫的 ConfigParser 模塊提供一套 API 來讀取和操作配置文件。因此在程序開始位置要導入該模塊,注意區分是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] # 對應的是一個sectionhost = 127.0.0.1 # 對應的是一個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) 設置 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)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
国产综合久久一区二区三区