[英]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.