私的AI研究会 > PyYaml
「pyyaml」はPython で簡単に YAML データを扱うことができライブラリ。
profile: nickname: ニックネーム
# コメントを書く
name: 太郎 age: 20
member: - 太郎 - 次郎 - 三郎
$ pip install pyyaml
x: XXX y: 100 z: [200, 300, 400]
import yaml with open('input.yaml') as file: obj = yaml.safe_load(file) print(obj['z'])
(py37) $ python3 yaml_sample.py [200, 300, 400]
#!/usr/bin/env python3 import yaml import sys try: with open('sample.yaml') as file: obj = yaml.safe_load(file) print(obj) except Exception as e: print('Exception occurred while loading YAML...', file=sys.stderr) print(e, file=sys.stderr) sys.exit(1)
(py37) $ python3 yaml_sample1.py Exception occurred while loading YAML... [Errno 2] No such file or directory: 'sample.yaml'
import yaml obj = { 'x': 'XXX', 'y': 100, 'z': [200, 300, 400] } print(yaml.dump(obj))
(py37) $ python3 yaml_sample2.py x: XXX y: 100 z: - 200 - 300 - 400
import codecs import yaml obj = { 'x': 'あいうえお', 'y': [1, 2, 3] } with codecs.open('output.yaml', 'w', 'utf-8') as f: yaml.dump(obj, f, encoding='utf-8', allow_unicode=True)
x: あいうえお y: - 1 - 2 - 3