Python 內建 ConfigParser 模組(Python 3 為 configparser)提供標準 INI 格式設定檔的讀寫支援,適用於應用程式參數外部化管理。本文示範基本讀取、修改與寫回流程。
testcfg.cfg[info]
age = 21
name = chen
gender = male
from __future__ import with_statement
import ConfigParser
config = ConfigParser.ConfigParser()
with open('testcfg.cfg', 'rw') as cfgfile:
config.readfp(cfgfile)
# 讀取值
name = config.get('info', 'name')
age = config.get('info', 'age')
print(name, age)
# 修改與新增
config.set('info', 'gender', 'male')
config.set('info', 'age', '22')
age = config.get('info', 'age')
print(name, age)
# 寫回檔案(需自行 open 寫入)
with open('testcfg.cfg', 'w') as f:
config.write(f)
config.get(section, option):回傳字串config.getint(section, option):回傳整數config.set(section, option, value):設定值(僅影響記憶體物件)config.write(fileobj):將完整結構寫入檔案config.has_section()、has_option():存在性檢查config.add_section():新增區塊from __future__ import with_statement 才能使用 with 語句open() 模式 'rw' 在 Python 2 無效,建議分別用 'r' 讀、'w' 寫[info])與選項名區分大小寫getint/float/boolean,其餘皆為字串