■ はじめに
https://dk521123.hatenablog.com/entry/2019/10/13/000000
で、YAMLを勉強したので、 今回は、それをPythonで扱ってみる
目次
【1】PyYAML のインストール 【2】サンプル 例1:YAMLの読み込み 例2:YAMLの読み込み その2 例3:YAML => JSON文字列 例4:YAML => JSONファイル 例5:YAMLのマージ
【1】PyYAML のインストール
pip install pyyaml
【2】サンプル
例1:YAMLの読み込み
hello.py
import yaml yaml_file = open('hello.yml', 'r') yaml_data = yaml.safe_load(yaml_file) print(yaml_data)
hello.yml
# YAML - Hello World - hello - world - 2019-12-21 - true - 45 - 3.12 - null - on
出力結果
['hello', 'world', datetime.date(2019, 12, 21), True, 45, 3.12, None, True]
例2:YAMLの読み込み その2
read_yaml.py
import yaml with open('sample.yaml', 'r') as yaml_file: yaml_data = yaml.safe_load(yaml_file) print('Name = ' + yaml_data['Name']) print('Value = ' + yaml_data['Value']) for friend in yaml_data['Friend']: print(friend['Name']) print(friend['Sex'])
sample.yaml
Name: 'Hello' Value: 'World!' Friend: - Name: 'Mike' Sex: 'Man' - Name: 'Tom' Sex: 'Man'
出力結果
Name = Hello Value = World! Mike Man Tom Man
例3:YAML => JSON
import yaml import json input_file = "hello.yaml" # dictをjson文字列に変換 output = json.dumps( # yaml文字列をdictに変換 yaml.load( # ファイルオープンし、読み出し open(input_file).read() ), # json文字列をインデントつきで出力 indent=2 ) print(output)
hello.yaml
Name: 'Hello' Value: 'World!' Friend: - Name: 'Mike' Sex: 'Man' - Name: 'Tom' Sex: 'Man'
出力結果
{ "Name": "Hello", "Value": "World!", "Friend": [ { "Name": "Mike", "Sex": "Man" }, { "Name": "Tom", "Sex": "Man" } ] }
例4:YAML => JSONファイル
import yaml import json input_file = "hello.yaml" output_file = "output.json" print("Start") with open(input_file, 'r') as yaml_file: yaml_data = yaml.safe_load(yaml_file) with open(output_file, 'w') as json_file: json.dump(yaml_data, json_file) print("Done")
output.json
{"Name": "Hello", "Value": "World!", "Friend": [{"Name": "Mike", "Sex": "Man"}, {"Name": "Tom", "Sex": "Man"}]}
例5:YAMLのマージ
import yaml with open('sample.yaml', 'r') as yaml_file: yaml_data = yaml.safe_load(yaml_file) with open('sample2.yaml', 'r') as yaml_file: yaml_data2 = yaml.safe_load(yaml_file) new_dict = dict(yaml_data, **yaml_data2) print(new_dict)
sample.yaml
Name: 'Hello' Value: 'World!' Friend: - Name: 'Mike' Sex: 'Man' - Name: 'Tom' Sex: 'Man'
sample2.yaml
Name: 'Hello2' Value2: 'World2!' Friend: - Name: 'Kevin' Sex: 'Man' - Name: 'Sam' Sex: 'Man'
出力結果
{ 'Name': 'Hello2', 'Value': 'World!', 'Friend': [ {'Name': 'Kevin', 'Sex': 'Man'}, {'Name': 'Sam', 'Sex': 'Man'} ], 'Value2': 'World2!'}
関連記事
YAML (YAML Ain't Markup Language)
https://dk521123.hatenablog.com/entry/2019/10/13/000000
Python ~ 基本編 / 文字列 ~
https://dk521123.hatenablog.com/entry/2019/10/12/075251
Python ~ 基本編 / 辞書 ~
https://dk521123.hatenablog.com/entry/2019/10/27/100014
Python ~ 基本編 / JSON ~
https://dk521123.hatenablog.com/entry/2019/10/19/104805
関数def (可変長引数 etc)
https://dk521123.hatenablog.com/entry/2019/09/22/000000