この記事では、設定ファイルとは何かを調べ、ConfigParserモジュールを使って、設定ファイルを作成し、設定ファイル内のデータを変更し、新しいデータを追加し、設定ファイルから既存のデータを削除します。
では、早速始めましょう。
Pythonの設定ファイルって何?
設定ファイル(config file)は、コンピュータプログラムの特定のデータや設定を保存する特別なファイルです。
ほとんどのコンピュータプログラムは、起動時に設定ファイルを読み込んで、定期的に設定ファイルの変更をチェックします。
このファイルを利用することで、プログラムを再コンパイルすることなく、アプリケーションの設定を変更することができます。
一般に、各設定ファイルは異なるセクションで構成されています。
各セクションは、Pythonの辞書のように、キーと値のペアを含んでいます。
以下は、住所、学歴、趣味の3つのセクションからなる設定ファイルの例です。
[Address]Name = Aditya Raj
Village = Bhojpur
District = Samastipur
State = Bihar
[Education]College=IIITA
Branch= IT
[Favorites]Sport = VolleyBall
Book = Historical Books
|
では、上記の設定ファイルをPythonのConfigParserモジュールを使って作ってみましょう。
Python ConfigParser モジュールを使って設定ファイルを作るには?
Pythonで設定ファイルを作成するために、configparserモジュールを使用します。
以下の実装では、ConfigParserオブジェクトを作成し、基本的にキーと値のペアを含む辞書であるセクションをそれに追加します。
そして、設定ファイルを.iniの拡張子で保存します。
#import moduleimport configparser
#create configparser objectconfig_file = configparser.ConfigParser()
#define sections and their key and value pairsconfig_file["Address"]={
"Name": "Aditya Raj",
"Village": "Bhojpur",
"District": "Samastipur",
"State": "Bihar"
}
config_file["Education"]={
"College":"IIITA",
"Branch" : "IT"
}
config_file["Favorites"]={
"Sports": "VolleyBall",
"Books": "Historical Books"
}
#SAVE CONFIG FILEwith open("person.ini","w") as file_object:
config_file.write(file_object)
print("Config file 'person.ini' created")
#print file contentread_file=open("person.ini","r")
content=read_file.read()
print("content of the config file is:")
print(content)
|
上記のコードスニペットの出力は以下の通りです。
Config file 'person.ini' created
content of the config file is:
[Address]name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
[Education]college = IIITA
branch = IT
[Favorites]sports = VolleyBall
books = Historical Books
|
ConfigParserで作成した設定ファイルに新しいセクションを追加する方法は?
設定ファイルに新しいセクションを追加するには、設定ファイルをconfigオブジェクトで読み込み、辞書形式でセクションを定義して新しいセクションを追加し、同じファイルにconfigオブジェクトを保存すればよいのです。
ここでは、アドレス、学歴、お気に入りのセクションを含むperson.iniファイルに、新しいセクション “Physique “を追加する例です。
import configparser
#print initial file contentread_file=open("person.ini","r")
content=read_file.read()
print("content of the config file is:")
print(content)
#create new config objectconfig_object= configparser.ConfigParser()
#read config file into objectconfig_object.read("person.ini")
#Add new section named Physiqueconfig_object["Physique"]={
"Height": "183 CM",
"Weight": "70 Kg"
}
#save the config object back to filewith open("person.ini","w") as file_object:
config_object.write(file_object)
#print the new config fileprint("Config file 'person.ini' updated")
print("Updated file content is:")
nread_file=open("person.ini","r")
ncontent=nread_file.read()
print(ncontent)
|
上記のコードスニペットの出力は以下の通りです。
content of the config file is:
[Address]name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
[Education]college = IIITA
branch = IT
[Favorites]sports = VolleyBall
books = Historical Books
Config file 'person.ini' updated
Updated file content is:
[Address]name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
[Education]college = IIITA
branch = IT
[Favorites]sports = VolleyBall
books = Historical Books
[Physique]height = 183 CM
weight = 70 Kg
|
また、add_section()メソッドを使用して新しいセクションを追加し、set()メソッドを使用してそのセクションに新しいフィールドを追加することもできます。
import configparser
#print initial file contentread_file=open("person.ini","r")
content=read_file.read()
print("content of the config file is:")
print(content)
#create new config objectconfig_object= configparser.ConfigParser()
#read config file into objectconfig_object.read("person.ini")
#Add new section named Physiqueconfig_object.add_section('Physique')
config_object.set('Physique', 'Height', '183 CM')
config_object.set('Physique', 'Weight', '70 Kg')
#save the config object back to filewith open("person.ini","w") as file_object:
config_object.write(file_object)
#print the updated config fileprint("Config file 'person.ini' updated")
print("Updated file content is:")
nread_file=open("person.ini","r")
ncontent=nread_file.read()
print(ncontent)
|
結果は以下の通りです。
結果は以下の通りです。
content of the config file is:
[Address]name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
[Education]college = IIITA
branch = IT
[Favorites]sports = VolleyBall
books = Historical Books
Config file 'person.ini' updated
Updated file content is:
[Address]name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
[Education]college = IIITA
branch = IT
[Favorites]sports = VolleyBall
books = Historical Books
[Physique]height = 183 CM
weight = 70 Kg
|
上の例では、add_section() メソッドはセクション名を引数に取り、set() メソッドはセクション名を第一引数に、フィールド名を第二引数に、フィールドの値を第三引数に取っていることが分かります。
この2つのメソッドは、新しい設定ファイルを作成する際にも使用することができます。
設定ファイルのデータを更新するには?
設定ファイルのセクションを辞書として定義しているので、辞書に適用できる操作は、設定ファイルのセクションにも適用できます。
辞書の項目で行うのと同様の方法で、設定ファイルの任意のセクションにフィールドを追加したり、フィールドの値を変更したりすることができます。
以下のコードでは、person.ini設定ファイルの「Education」セクションに新しいフィールド「Year」を追加し、ファイル内の「Branch」フィールドの値を変更しています。
import configparser
#print initial file contentread_file=open("person.ini","r")
content=read_file.read()
print("content of the config file is:")
print(content)
#create new config objectconfig_object= configparser.ConfigParser()
#read config file into objectconfig_object.read("person.ini")
#update value of a field in a sectionconfig_object["Education"]["Branch"]="MBA"
#add a new field in a sectionconfig_object["Education"].update({"Year":"Final"})
#save the config object back to filewith open("person.ini","w") as file_object:
config_object.write(file_object)
#print updated contentprint("Config file 'person.ini' updated")
print("Updated file content is:")
nread_file=open("person.ini","r")
ncontent=nread_file.read()
print(ncontent)
|
結果は以下の通りです。
content of the config file is:
[Address]name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
[Education]college = IIITA
branch = IT
[Favorites]sports = VolleyBall
books = Historical Books
[Physique]height = 183 CM
weight = 70 Kg
Config file 'person.ini' updated
Updated file content is:
[Address]name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
[Education]college = IIITA
branch = MBA
year = Final
[Favorites]sports = VolleyBall
books = Historical Books
[Physique]height = 183 CM
weight = 70 Kg
|
上記の例では、update() メソッドを使用して、新しいフィールドを追加したり、既存のフィールドを変更したりすることができます。
引数として与えられたフィールドがファイル内に存在すれば、そのフィールドを更新し、そうでなければ新しいフィールドを作成します。
How to delete data from config file?
configparserモジュールの remove_option() と remove_section() モジュールを使って、コンフィグファイルからデータを削除することができます。
remove_option()は任意のセクションからフィールドを削除するために、remove_section()`は設定ファイルのセクション全体を削除するために使用されます。
import configparser
#print initial file contentread_file=open("person.ini","r")
content=read_file.read()
print("content of the config file is:")
print(content)
#create new config objectconfig_object= configparser.ConfigParser()
#read config file into objectconfig_object.read("person.ini")
#delete a field in a sectionconfig_object.remove_option('Education', 'Year')
#delete a sectionconfig_object.remove_section('Physique')
#save the config object back to filewith open("person.ini","w") as file_object:
config_object.write(file_object)
#print new config fileprint("Config file 'person.ini' updated")
print("Updated file content is:")
nread_file=open("person.ini","r")
ncontent=nread_file.read()
print(ncontent)
|
結果は以下の通りです。
結果は以下の通りです。
content of the config file is:
[Address]name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
[Education]college = IIITA
branch = MBA
year = Final
[Favorites]sports = VolleyBall
books = Historical Books
[Physique]height = 183 CM
weight = 70 Kg
Config file 'person.ini' updated
Updated file content is:
[Address]name = Aditya Raj
village = Bhojpur
district = Samastipur
state = Bihar
[Education]college = IIITA
branch = MBA
[Favorites]sports = VolleyBall
books = Historical Books
|
上の例では、remove_option()メソッドが第一引数にセクション名、第二引数にフィールド名を取るのに対し、remove_section()メソッドは削除するセクション名を引数に取っていることが分かります。
まとめ
この記事では、設定ファイルとは何か、そしてPython configparserモジュールを使って設定ファイルを作成し操作する方法について見てきました。
参考文献 – https://docs.python.org/3/library/configparser.html