pythonで設定ファイル

pythonで設定ファイルを使う

サーバ名やユーザID・パスワード、参照先のパスなど、オンコーディングしたくない値がどうしてもある。そんなとき、pythonではiniファイル形式の設定ファイルを簡単に扱えるモジュールが標準機能で準備してある。

実装例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import ConfigParser
'python3ではimport configparser'

'''設定ファイルの作成'''
s_config = ConfigParser.ConfigParser()
'python3ではs_config = configparser.ConfigParser()'
s_config.add_section('Section1')
s_config.set('Section1', 'Key1', 'Value1')
s_config.set('Section1', 'Key2', 'Value2')
s_config.add_section('Section2')
s_config.set('Section2', 'Key3', 'Value4')
s_config.set('Section2', 'Key4', 'Value4')
with open('Config.ini', 'wb') as w:
    s_config.write(w)

'''設定ファイルの読み込み'''
r_config = ConfigParser.ConfigParser()
r_config.read('Config.ini')
print(r_config.get('Section1', 'Key1'))
print(r_config.get('Section2', 'Key4'))

このサンプルでは、iniファイルの作成もプログラムで行なっているが、iniファイル形式のファイルなので、テキストエディタで直接、設定ファイルを作成しても問題ない。

ちなみに、上記の例で作成されるConfig.iniは下記の通り。

[Section1]
key1 = Value1
key2 = Value2

[Section2]
key3 = Value4
key4 = Value4
同じタグの記事
同じカテゴリの記事

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA