问题
I have a YAML file called data.yaml
:
---
'001':
name: Ben
email: ben@test.com
I would like to have an updated file that looks like this:
---
'001':
name: Ben
email: ben@test.com
'002':
name: Lisa
email: lisa@test.com
numbers:
- 000-111-2222
- 000-111-2223
How do I achieve this in python using yaml package/s?
Edit:
I have tried:
import yaml
import io
data = {'002': {'name': 'Lisa', 'email': 'lisa@test.com', 'numbers': ['000-111-2222', '000-111-2223']}}
with io.open('data.yaml', 'w', encoding='utf8') as outfile:
yaml.safe_dump(data, outfile, default_flow_style=False, allow_unicode=True)
Method safe_dump overrides the file content and I only see this as the new file content!
'002':
name: Lisa
email: lisa@test.com
numbers:
- 000-111-2222
- 000-111-2223
回答1:
You can, in general, not add to a YAML document in a file by just writing extra information at the end of that file. This migth work for YAML documents that have a mapping or sequence at the top level that is block style, but even then simply appending can only work for certain cases of documents.
It is easy to just load your YAML to Python datastructure,
update/extend that structure and then dump it back. That way you don't
have to deal with potential duplicate keys, non-bare documents and
other issues that will result in invalid YAML when you use simple
appending. Assumping your original file is called input.yaml
, the
following does the trick:
import sys
from pathlib import Path
import ruamel.yaml
file_name = Path('input.yaml')
record_to_add = dict(name='Lisa', email='lisa@test.com', numbers=['000-111-2222', '000-111-2223'])
yaml = ruamel.yaml.YAML()
yaml.explicit_start = True
data = yaml.load(file_name)
data['002'] = record_to_add
yaml.dump(data, sys.stdout)
which gives:
---
'001':
name: Ben
email: ben@test.com
'002':
name: Lisa
email: lisa@test.com
numbers:
- 000-111-2222
- 000-111-2223
来源:https://stackoverflow.com/questions/54627042/how-do-i-append-to-a-yaml-file-with-python