如何使用python附加到YAML文件 [英] How do I append to a YAML file with python

查看:155
本文介绍了如何使用python附加到YAML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为data.yaml的YAML文件:

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

如何使用yaml包在python中实现此目标?

How do I achieve this in python using yaml package/s?

我尝试过:

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)

方法 safe_dump 会覆盖文件内容,我只能将其视为新文件内容!

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

推荐答案

通常,您可以只写一些额外的代码就不会将其添加到文件中的YAML文档中. 该文件末尾的信息.此migth适用于具有以下内容的YAML文档: 顶层的块映射或序列,甚至 那么仅附加文件仅适用于某些情况下的文件.

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.

将YAML加载到Python数据结构很容易, 更新/扩展该结构,然后将其转回.这样你就不会 必须处理潜在的重复密钥,非裸露的文件和 使用简单时会导致无效YAML的其他问题 附加中.假设您的原始文件称为input.yaml, 以下是窍门:

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)

给出:

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

这篇关于如何使用python附加到YAML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆