name: John Smith
age: 37
spouse:
name: Jane Smith
age: 25
children:
- name: Jimmy Smith
age: 15
- name: Jenny Smith
age: 12
和它对应的json文件如下:
{ name: 'John Smith',
age: 37,
spouse: { name: 'Jane Smith', age: 25 },
children:
[ { name: 'Jimmy Smith', age: 15 },
{ name: 'Jenny Smith', age: 12 } ]
}
import yaml
if __name__ == "__main__":
with open('father.yml') as f:
content = yaml.load(f)
# output: <type 'dict'>
print(type(content))
print(content)
content.update({'age': 38})
print(content)
with open('PyYAML.yml', 'w') as nf:
yaml.dump(content, nf)
生成的新yaml文件形式如下:
age: 38
children:
- {age: 15, name: Jimmy Smith}
- {age: 12, name: Jenny Smith}
name: John Smith
spouse: {age: 25, name: Jane Smith}
仔细一看,跟原yaml文件不像嘛,尤其是几个大括号,很刺眼,这可怎么办?
from ruamel import yaml
if __name__ == "__main__":
with open('father.yml') as f:
content = yaml.load(f, Loader=yaml.RoundTripLoader)
# output: <type 'dict'>
print(type(content))
print(content)
content.update({'age': 38})
print(content)
with open('ruamel.yml', 'w') as nf:
yaml.dump(content, nf, Dumper=yaml.RoundTripDumper)
生成新的yaml文件形式如下,正是我们期望的格式:
name: John Smith
age: 38
spouse:
name: Jane Smith
age: 25
children:
- name: Jimmy Smith
age: 15
- name: Jenny Smith
age: 12
本文代码已经归档到github,您可以访问下面的链接获得,欢迎star该代码仓库。
代码地址