How do I append to a YAML file with python

好久不见. 提交于 2019-12-20 07:15:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!