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)