LoginSignup
15
14

More than 5 years have passed since last update.

PythonでTOMLファイルを編集したい

Posted at

この記事は?

ちょっと、PythonでTOMLファイルを編集したいことがあったので、その方法についてメモ。

TOMLとは?

こちらの記事がわかりやすいと思います。

設定ファイル記述言語 TOML

簡単にいうと、設定ファイル記述言語で、yamlとかJSONとかの類です。
少し触った程度ですが、yamlよりもシンプルで見やすいと思います。

やりかた

簡単なTOMLファイルを用意します。

example.toml
[table]
key = "value"

[table.subtable]
key = "another value"

ライブラリのインストール

TOMLのライブラリはまだPythonの標準ライブラリなどには含まれていないので、pipなどでインストールします。

こちらのライブラリを使用します。

インストールコマンドはこんな感じ

pip install toml

TOMLファイルの読み込み

ライブラリが入ると後は簡単にできます。

index.py
import toml

dict_toml = toml.load(open('example.toml'))
print(dict_toml)

組み込み関数のopenでtomlファイルを開きtoml.loadで読み込んで、tomlファイルの中身を辞書型にして返しています。

実行結果は以下

{'table': {'key': 'value', 'subtable': {'key': 'another value'}}}

辞書型なので、keyを指定することでvalueを取得できます。

index.py
import toml

dict_toml = toml.load(open('example.toml'))

print(dict_toml['table']['key'])
# 出力
# value

TOMLファイルの書き換え

書き換えもできます。
例えば、subtableanother valuesubtable valueと変えたい場合は以下のようになります。

index.py
import toml

dict_toml = toml.load(open('example.toml'))
dict_toml['table']['subtable']['key'] = "subtable value"

toml.dump(dict_toml, open('example.toml', mode='w'))

一度、example.tomlを読み込んで、dict_toml['table']['subtable']['key'] = "subtable value"で値を書き換えて、再び組み込み関数のopenexample.tomlを今度は書き込みモードで開いて、toml.dumpを使って書き込んでいます。

これを実行した後のexample.tomlはこんな感じになっています。

example.toml
[table]
key = "value"

[table.subtable]
key = "subtable value"

ちゃんと書き換わっていますね。

終わりに

こんな感じでTOMLファイルの編集が簡単にできました。
機会があれば使ってみてください。

以上

15
14
0

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
15
14