Python の configparser の引数 defaults

データ

以下のデータを読み込みます.セクション「DEFAULT」が設定されています.このセクションで設定されたキーと値は,他のすべてのセクションにも反映されます.

# configparser を使ったインプットファイルの例

[DEFAULT]
  title:         Blue Sky
  photographer:  Masashi Yamamoto
  date:          2017/12/30

[camera setting]
  F値:          2.8
  シャッター速度: 1/60
  ISO感度:        4000

[smartphone]
  maker:         HUAWEI
  type:          P10 lite

プログラム

コンストラクターの引数に defaults の値を辞書型データで指定します.これは,セクション [DEFAULT] のデフォルトの値になります.

#!/usr/bin/python3
import configparser

dat = configparser.ConfigParser(
    defaults={'title':'no_title', 'place':'Tokyo'})
dat.read('sample.dat')

for section in dat.sections():
    for key in dat[section]:
        print(section, '>', key, ':', dat[section][key])
    print()

実行結果

以下に実行結果を示します.コンストラクターの引数はデフォルト値であるため,キー「title」はファイルに書かれた値が反映されます.一方,キー「place」はファイルに書かれていないため,引数のデフォルトの値になります.

camera setting > f値 : 2.8
camera setting > シャッター速度 : 1/60
camera setting > iso感度 : 4000
camera setting > title : Blue Sky
camera setting > place : Tokyo
camera setting > photographer : Masashi Yamamoto
camera setting > date : 2017/12/30

smartphone > maker : HUAWEI
smartphone > type : P10 lite
smartphone > title : Blue Sky
smartphone > place : Tokyo
smartphone > photographer : Masashi Yamamoto
smartphone > date : 2017/12/30