python yaml

17 篇文章 0 订阅

pip install pyaml

references: https://pyyaml.org/wiki/PyYAMLDocumentation

1. yaml文件示例

yaml0.yaml

- a: b
- c: d
  e: f
  h: i

 

2. 代码

In [1]: from ruamel import yaml

In [2]: f = open('yaml0.yaml', 'r')

In [3]: a = f.read()

In [4]: a
Out[4]: '- a: b\n- c: d\n  e: f\n  h: i'

In [5]: b = yaml.load(a)
c:\users\machenike\appdata\local\programs\python\python36\Scripts\ipython:1: UnsafeLoaderWarning:
The default 'Loader' for 'load(stream)' without further arguments can be unsafe.
Use 'load(stream, Loader=ruamel.yaml.Loader)' explicitly if that is OK.
Alternatively include the following in your code:

  import warnings
  warnings.simplefilter('ignore', ruamel.yaml.error.UnsafeLoaderWarning)

In most other cases you should consider using 'safe_load(stream)'

In [6]: b
Out[6]: [{'a': 'b'}, {'c': 'd', 'e': 'f', 'h': 'i'}]

In [7]: c = yaml.safe_load(a)

In [8]: c
Out[8]: [{'a': 'b'}, {'c': 'd', 'e': 'f', 'h': 'i'}]

In [9]: d = yaml.dump(c)

In [10]: d
Out[10]: '- {a: b}\n- {c: d, e: f, h: i}\n'

In [11]: print(d
    ...: )
- {a: b}
- {c: d, e: f, h: i}


In [12]: import yaml

In [13]: yaml.dump(c)
Out[13]: '- {a: b}\n- {c: d, e: f, h: i}\n'

In [14]: e = yaml.dump(c)

In [15]: import json

In [16]: json.dumps(e)
Out[16]: '"- {a: b}\\n- {c: d, e: f, h: i}\\n"'

In [17]: f = json.dumps(e)

In [18]: f
Out[18]: '"- {a: b}\\n- {c: d, e: f, h: i}\\n"'

In [19]: yaml.safe_load(json.loads(f))
Out[19]: [{'a': 'b'}, {'c': 'd', 'e': 'f', 'h': 'i'}]

In [20]:

In [37]: yaml.dump(c, default_flow_style=False)
Out[37]: '- a: b\n- c: d\n  e: f\n  h: i\n'

In [38]: ccc = yaml.dump(c, default_flow_style=False)

In [39]: print(ccc)
- a: b
- c: d
  e: f
  h: i


In [40]:

yaml.dump(c, default_flow_style=False)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值