dak ブログ

python、rubyなどのプログラミング、MySQL、サーバーの設定などの備忘録。レゴの写真も。

python での yaml ファイルの読み込み

2021-09-19 23:34:02 | python
python での yaml ファイルの読み込み方法のメモ。

python で yaml を処理するためのライブラリの pyyaml をインストールします。
pip install pyyaml

以下のようにして pyyaml で yaml ファイルを読み込めます。
import sys
import yaml

def main():
    file = sys.argv[1]
    try:
        with open(file) as f:
            obj = yaml.safe_load(f)
            print(type(obj))
            print(obj)
    except:
        sys.stderr.write('error: failed to open %s\n' % (file))
        return 1

    return 0

if __name__ == '__main__':
    res = main()
    exit(res)
 

上記のプログラムに以下の yaml ファイルを読み込ませてみます。
db:
  host: localhost
  port: 3306
  db:   test-user

vals1:
  - a
  - b
  - c

vals2: [a, b, c]

実行結果は以下のようになります。
'db': {'host': 'localhost', 'port': 3306, 'db': 'test-user'}, 'vals1': ['a', 'b', 'c'], 'vals2': ['a', 'b', 'c']}


この記事についてブログを書く
« python でのコマンドライン引... | トップ | python から java プログラム... »

python」カテゴリの最新記事