简体   繁体   English

如何使用python附加到YAML文件

[英]How do I append to a YAML file with python

I have a YAML file called data.yaml : 我有一个名为data.yaml的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? 如何使用yaml包在python中实现此目标?

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! 方法safe_dump会覆盖文件内容,我只能将其视为新文件内容!

'002':
  name: Lisa
  email: lisa@test.com
  numbers: 
    - 000-111-2222
    - 000-111-2223

You can, in general, not add to a YAML document in a file by just writing extra information at the end of that file. 通常,仅在文件末尾写一些额外的信息就不能将其添加到文件中的YAML文档中。 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. 这种过渡适用于在顶层具有块样式的映射或序列的YAML文档,但是即使这样,仅附加操作也仅适用于某些情况。

It is easy to just load your YAML to Python datastructure, update/extend that structure and then dump it back. 只需将YAML加载到Python数据结构,更新/扩展该结构,然后将其转储回去,就很容易。 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. 这样,您就不必处理潜在的重复密钥,非裸露的文档以及其他在使用简单追加时将导致无效YAML的问题。 Assumping your original file is called input.yaml , the following does the trick: 假设您的原始文件称为input.yaml ,则可以完成以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM