萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python ConfigParser 讀寫 INI 設定檔完整教學

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():新增區塊

常見坑點提醒

  1. Python 2 需 from __future__ import with_statement 才能使用 with 語句
  2. open() 模式 'rw' 在 Python 2 無效,建議分別用 'r' 讀、'w' 寫
  3. 區塊名([info])與選項名區分大小寫
  4. 值自動轉型僅限 getint/float/boolean,其餘皆為字串
copyright © 萬盛學電腦網 all rights reserved