Pythonで設定ファイルを扱う方法:ConfigParser
Pythonで設定ファイルを扱う場合はConfigParserモジュールを使うと便利です。今回はConfigParserの使い方について紹介します。
設定ファイルの構成
ConfigParserで読み込み可能な設定ファイルのフォーマットは以下のような形になります。
[セクション1] オプション1 = 値1 オプション2 = 値2 [セクション2] オプション3 = 値3 オプション4 = 値4
設定ファイルは直接ファイルに記述することもできますが、ConfigParserモジュールを使うことで簡単にフォーマットした設定ファイルを作成することができます。
設定ファイルを作成する
セクションを追加するときはadd_section()メソッドを使います。引数はセクション名を表す文字列です。次にセクションの中へ、オプションと値の組を追加していきます。set() メソッドを使って、セクション名、オプション名、値をそれぞれ渡します。
import ConfigParser
config = ConfigParser.ConfigParser()
section1 = 'development'
config.add_section(section1)
config.set(section1, 'host', 'localhost')
config.set(section1, 'port', 10001)
section2 = 'production'
config.add_section(section2)
config.set(section2, 'host', 'xxx.co.jp')
config.set(section2, 'port', 10002)
with open('setting.ini', 'w') as file:
config.write(file)
設定ファイルへ書き込むときはwrite()メソッドにファイルオブジェクトを渡します。
上のプログラムを実行すると、以下のような設定ファイル(setting.ini)が作成されます。
$ cat setting.ini [development] host = localhost port = 10001 [production] host = xxx.co.jp port = 10002
設定ファイルを読み込む
read()メソッドの引数にファイル名を渡すことで、設定ファイルを読み込むことができます。オプションの値は get()で取得することができます。以下は、先ほど作成した「setting.ini」ファイルを読み込む例です。
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('setting.ini')
section1 = 'development'
print config.get(section1, 'host') # localhost
print config.get(section1, 'port') # 10001
section2 = 'production'
print config.get(section2, 'host') # xxx.co.jp
print config.get(section2, 'port') # 10002
また、セクションが定義されているかどうか確認するためにはhas_section()メソッドを使います。
print config.has_section('production')  # True
print config.has_section('staging')     # false
セクション内にオプションが定義されているかどうか確認するためにはhas_option()メソッドを使います。
print config.has_option('production', 'host') # true
print config.has_option('production', 'user') # false
options() メソッド を使うと、セクション内のオプション一覧をリストとして取得できます。また、items() はオプションと値のペアをリストで返します。
print config.options('development') # ['host', 'port']
print config.items('development')   # [('host', 'localhost'), ('port', '10001')]