import sys
from ruamel.yaml import YAMLinp ="""\
# example
name:# detailsfamily: Smith # very commongiven: Alice # one of the siblings
"""yaml = YAML()
code = yaml.load(inp)
code['name']['given']='Bob'yaml.dump(code, sys.stdout)
结果是:
# example
name:# detailsfamily: Smith # very commongiven: Bob # one of the siblings
5 使用旧API将YAML解析为Python对象并修改
from __future__ import print_functionimport sys
import ruamel.yamlinp ="""\
# example
name:# detailsfamily: Smith # very commongiven: Alice # one of the siblings
"""code = ruamel.yaml.load(inp, ruamel.yaml.RoundTripLoader)
code['name']['given']='Bob'ruamel.yaml.dump(code, sys.stdout, Dumper=ruamel.yaml.RoundTripDumper)# the last statement can be done less efficient in time and memory with# leaving out the end='' would cause a double newline at the end# print(ruamel.yaml.dump(code, Dumper=ruamel.yaml.RoundTripDumper), end='')
结果是:
# example
name:# detailsfamily: Smith # very commongiven: Bob # one of the siblings
import sys
from ruamel.yaml import YAMLyaml_str ="""\
first_name: Art
occupation: Architect # This is an occupation comment
about: Art Vandelay is a fictional character that George invents...
"""yaml = YAML()
data = yaml.load(yaml_str)
data.insert(1,'last name','Vandelay', comment="new key")
yaml.dump(data, sys.stdout)
结果为以下,可以发现插入了数据last name: Vandelay
first_name: Art
last name: Vandelay # new key
occupation: Architect # This is an occupation comment
about: Art Vandelay is a fictional character that George invents...