LoginSignup
4
1

More than 5 years have passed since last update.

Python2のConfigParserで読み込んだ設定ファイルの内容を辞書型で扱えるようにする

Last updated at Posted at 2018-03-20

以下のようなINIファイル形式の設定ファイルがあったとします。

[Section1]
foo=bar

Python3のconfigparserモジュールでは読み込んだINIファイルを辞書型で扱えます。

import configparser
config = configparser.ConfigParser()
print(config["Section1"]["foo"]) #-> "bar"

Python2のConfigParserモジュールでは辞書型でのアクセスが用意されておらず、Python3のconfigparserモジュールと同様の事をしようとするとエラーになります。
Python2のConfigParserモジュールではINIファイルの内容を取得するにはConfigParser.get()メソッドを使います。

import ConfigParser
config = Configparser.ConfigParser()
print(config["Section1"]["foo"]) #-> AttributeError!!!
print(config.get("Section1", "foo")) #-> "bar"

しかし、辞書型で扱えたほうが便利な事が多々あります。ConfigParserクラスにはセクションの一覧を取得するメソッドConfigParser.sections()と、指定したセクションのそれぞれのオプションの(name, value)のペアのリストを取得するConfigParser.items()があるので、これらを使用してひと手間加えることで辞書型での取得が可能になります。

import ConfigParser
config = Configparser.ConfigParser()
config_dict = {s: {i[0]: i[1] for i in config.items(s)}
               for s in config.sections()}
print(config_dict["Section1"]["foo"]) #-> "bar"
4
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1