如何在python3中使用yaml转储保留格式
我只想使用 python 更改以下 yaml 文件中的属性 anotherName。
test.yaml:
---
kind: test
scope: not far
spec:
test1:
options:
- name: test.com
anotherName: example.com
empty: []
groupOne: []
emptyList:
firstList: []
secondList: []
代码(基于这个答案)
import yaml
with open("test.yaml", 'r') as stream:
try:
loaded=yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
temp= loaded['spec']['test1']['options']
for elem in temp:
elem['anotherName']='somethingChanged'
with open("modified.yaml", 'w') as stream:
try:
yaml.dump(loaded, stream)
print(loaded)
except yaml.YAMLError as exc:
print(exc)
值已更改,但代码更改了modified.yaml<的顺序和结构< /强>:
#First it misses the thre dashes
kind: test
scope: not far
spec:
test1:
emptyList:
firstList: []
secondList: []
groupOne: []
options:
- anotherName: somethingChanged #then the order is changed
empty: []
name: test.com
I want to change only the attribute anotherName from the following yaml file with python.
test.yaml:
---
kind: test
scope: not far
spec:
test1:
options:
- name: test.com
anotherName: example.com
empty: []
groupOne: []
emptyList:
firstList: []
secondList: []
Code (based on this answer)
import yaml
with open("test.yaml", 'r') as stream:
try:
loaded=yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
temp= loaded['spec']['test1']['options']
for elem in temp:
elem['anotherName']='somethingChanged'
with open("modified.yaml", 'w') as stream:
try:
yaml.dump(loaded, stream)
print(loaded)
except yaml.YAMLError as exc:
print(exc)
The value has been changed, but the code change the order and the structure of the modified.yaml :
#First it misses the thre dashes
kind: test
scope: not far
spec:
test1:
emptyList:
firstList: []
secondList: []
groupOne: []
options:
- anotherName: somethingChanged #then the order is changed
empty: []
name: test.com
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的 PyYAML 版本高于 5.1,您可以使用
sort_keys
参数来保留顺序。唯一需要更改的行是这一行:If your version of PyYAML is higher than 5.1 you can use
sort_keys
argument to preserve the order. The only line that needs change is this one:你可能无法强制 pyyaml 输出特定的输出,但如果你有这样一个特定的要求,你想用什么来替代,那么为什么还要额外麻烦地解析 yml fromat 呢。将文件读入字符串然后进行替换怎么样:
输出:
you can probably not force a specific output from pyyaml, but if you have such a specific requirement what you want to substitute, then why make the extra hassel of parsing the yml fromat at all. How about reading the file into a string and then making your replacement:
Output: