繁体   English   中英

如何在python的YAML文件中添加新字段?

[英]How do I add a new field to a YAML file in python?

我有一个包含内容的YAML文件:

---
  'Croatia':
    population: 4600000
    capital: Zagreb
  'Italy':
    population: 60000000
    capital: Rome

我要如何添加新字段:

---
  'Croatia':
    population: 4600000
    capital: Zagreb
    continent: Europe
  'Italy':
    population: 60000000
    capital: Rome
    continent: Europe

如何向每个州添加具有欧洲价值的“大陆”字段?

加载它,像往常一样在字典中更新该字段,然后再次转储。

data = yaml.load(...)
data['Croatia']['continent'] = 'Europe'
yaml.dump(data, ...)

如果您想保留原始的YAML布局和引用,那么通常不需花费大量精力就可以使用pyyaml做到这一点。

使用ruamel.yaml (免责声明:我是该程序包的作者),这要简单得多,但是您仍然需要为顶层缩进做两个空格(使用transform参数):

import sys
import ruamel.yaml

yaml_str = """\
---
  'Croatia':
    population: 4600000
    capital: Zagreb
"""

def indent_data(s):
    return s.replace('\n', '\n  ')

yaml = ruamel.yaml.YAML()
# yaml.indent(mapping=4, sequence=4, offset=2)
yaml.preserve_quotes = True
yaml.explicit_start = True
data = yaml.load(yaml_str)
data['Croatia']['continent'] = 'Europe'
yaml.dump(data, sys.stdout, transform=indent_data)

给出:

---
  'Croatia':
    population: 4600000
    capital: Zagreb
    continent: Europe

原始文档中的任何注释都将保留在输出中,但是由于额外的缩进,EOL注释可能会发生变化。

暂无
暂无

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

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