[最終更新] 2017年2月21日
pythonのPyYAMLでYAMLを取り扱うとき、出力はyaml.dump()を使いますが、ブロックスタイルで出力したいのにフロートスタイルで出力されることもあります。ブロックスタイルに指定して出力するには、オプションとしてdefault_flow_style=Falseを加えます。
サンプル
Python 3.5 + PyYAMLにて、yaml.dump()でブロックスタイルで出力します。オプションに、default_flow_style=FalseとすればOKです。
サンプルを以下に。
$ python
>>> import yaml
>>> sample = {'apple': 100, 'ringo': 200}
# フロートスタイル(デフォルト)
>>> print(yaml.dump(sample))
{apple: 100, ringo: 200}
# ブロックスタイル
>>> print(yaml.dump(sample, default_flow_style=False))
apple: 100
ringo: 200
参考:「PyYAMLDocumentation – PyYAML」
関連記事
Python の記事
- [2017年12月27日] Pandasで行の追加(縦方向の連結)の操作メモ
- [2017年12月25日] PDFから文章を抽出する
- [2017年12月25日] seleniumのGoogle検索で最初にヒットしたサイトのスクリーンショットを撮る
- [2017年12月22日] pythonでExcelファイル内の半角をすべて全角にする
- [2017年11月14日] pythonのxlsxwriterでフォーマットの上書きをしたいが…
- ---本記事---
- [2016年10月4日] 旧版:とにかくRaspberry Piにpython3 + numpy + matplotlibをインストールする(pyenv使用)
- [2016年8月3日] Python3で意図せずしてfloatに…VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
- [2015年12月17日] matplotlib も十分わかりやすく思えてしまう
- [2015年9月16日] Python でクロスプラットフォームの排他ロックはなかなか難しく
- [2015年8月5日] Raspbian で python-dev がインストールできなかった
スポンサーリンク