How can I parse a YAML file in Python?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Example:
defaults.yaml
environment.py
Import yaml module and load the file into a dictionary called 'my_dict':
That's all you need. Now the entire yaml file is in 'my_dict' dictionary.
I use ruamel.yaml.
Details & debate here.Usage of ruamel.yaml is compatible (with some simple solvable problems) with old usages of PyYAML and as it is stated in link I provided, use
instead of
and it will fix most of your problems.
EDIT: PyYAML is not dead as it turns out, it's just maintained in a different place.
If you have YAML that conforms to the YAML 1.2 specification (released 2009) then you should use ruamel.yaml (disclaimer: I am the author of that package). It is essentially a superset of PyYAML, which supports most of YAML 1.1 (from 2005).
If you want to be able to preserve your comments when round-tripping, you certainly should use ruamel.yaml.
Upgrading @Jon's example is easy:
Use
safe_load()
unless you really have full control over the input, need it (seldom the case) and know what you are doing.If you are using pathlib
Path
for manipulating files, you are better of using the new API ruamel.yaml provides:Read & Write YAML files with Python 2+3 (and unicode)
Created YAML file
Common file endings
.yml
and.yaml
Alternatives
For your application, the following might be important:
See also: Comparison of data serialization formats
In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python