yamlファイルを扱う

Pythonyamlファイルの読み書きを行う。
参考:http://gihyo.jp/dev/serial/01/yaml_library/0003?page=1
まずは、PyYAMLモジュールをインストールしてみた。使ってみる。
こんな風に記述されているyamlファイル(test.yaml)。

Event:
  Obj1:
    Data: 2010/0330
    Place: here
    Zip:
    - {Num: 10002, Add: place1}
    - {Num: 10003, Add: place2}
  Obj2:
    Data: 2009/0112
    Place: somewhere
    Zip:
    - abcdefg
    - 1234567

を読むスクリプトは以下の通り。

import yaml

string = open('test.yaml').read()
data = yaml.load(string)
val = data['Event']

print val.keys()

for k, v in val.iteritems():
    print k, v

fp = open('writeout.yaml', 'w')
yaml.dump(val, fp)

実行結果は下の通り。

>>>
['Obj1', 'Obj2']
Obj1 {'Data': '2010/0330', 'Place': 'here', 'Zip': [{'Add': 'place1', 'Num': 10002}, {'Add': 'place2', 'Num': 10003}]}
Obj2 {'Data': '2009/0112', 'Place': 'somewhere', 'Zip': ['abcdefg', 1234567]}

書き出されたファイル(writeout.yaml)は、

Obj1:
  Data: 2010/0330
  Place: here
  Zip:
  - {Add: place1, Num: 10002}
  - {Add: place2, Num: 10003}
Obj2:
  Data: 2009/0112
  Place: somewhere
  Zip: [abcdefg, 1234567]

ブロックスタイル(インデントで構造を記述する)とフロースタイル({}や[]で構造を記述する)が混在するのが嫌な場合は、default_flow_style=Falseとしてdumpする。

yaml.dump(val, fp, default_flow_style=False)

その結果は、

Obj1:
  Data: 2010/0330
  Place: here
  Zip:
  - Add: place1
    Num: 10002
  - Add: place2
    Num: 10003
Obj2:
  Data: 2009/0112
  Place: somewhere
  Zip:
  - abcdefg
  - 1234567

となる。