my学備忘録

忘れっぽいエンジニア(一応)が勉強のために残す備忘録ブログ。技術系を中心にや読んだ本とか勉強になったことなど。

【python】【ini】Pythonでiniファイル読み込み

前回のiniファイルの続き。

mame-bibouroku.hatenablog.com

pythonでiniファイルを読み込みます。

使用するiniファイルは、適当に作ったこちらを使用。

[network_config]
ipaddress=127.0.0.1
port=5963

[graphics]
height=100
width=200
fps=60

[sound]
bgm=100

適当さがにじみ出ているiniファイルですが、 セクションとパラメータがいくつか並んでいます。 とりあえずそれぞれが取得できるようにプログラムを組んでみます。

test_ini_read.py

# -*- coding: UTF-8 -*-

import ConfigParser

conf_parser = ConfigParser.ConfigParser()

# ConfigParserによりiniファイルを読み込み
conf_parser.read('test_conf.ini')

#sectionリストを取得
section_list = conf_parser.sections()

print "sections", conf_parser.sections(),"\n"

for section  in section_list:
    #sectionデータからオプションリストを取得
    print section, "options ",conf_parser.options(section)
    # 辞書型でセクションごとのパラメータ取得
    get_data = conf_parser.items(section)
    print get_data, "\n"

出力結果

[vagrant@localhost python]$ python test_ini_read.py
sections ['network_config', 'graphics', 'sound']

network_config options  ['ipaddress', 'port']
[('ipaddress', '127.0.0.1'), ('port', '5963')]

graphics options  ['height', 'width', 'fps']
[('height', '100'), ('width', '200'), ('fps', '60')]

sound options  ['bgm']
[('bgm', '100')]

基本的には、iniファイルを読み込んでsectionのリストを取得し、

辞書型に入れていくのが良いんでしょうか?

テストという事で、セクションごとに辞書型に入れていますが、

あらかじめ宣言しておいて、セクション名→(パラメータ名,データ)みたいな形で登録出来れば、

使い勝手は良さそうかも?

設定値を変えて色々試したいプログラム等には役に立ちそうです。