我在StackOverflow上发现了类似的问题,但是当我尝试实现适合自己情况的代码[Anthons's response]时,我注意到它实际上并没有编辑YAML文件。另外,我需要使用ruamel.yaml,而不是PyYAML。我评论过的许多答案都使用PyYAML。
import sys
import ruamel.yaml
yaml = ruamel.yaml.YAML()
# yaml.preserve_quotes = True
with open('elastic.yml') as fp:
data = yaml.load(fp)
data['cluster.name'] = 'BLABLABLABLABLA'
data['node.name'] = 'HEHEHEHEHEHEHE'
yaml.dump(data, sys.stdout)
此代码以正确的编辑输出文件,但是,当我实际进入文件(elastic.yml
)时,原始文档没有更改。
这是我第一次接触ruamel.yaml,我宁愿坚持这一点,因为我注意到PyYAML不会保留评论。
运行python代码后的YAML文件:
cluster.name: my-application
# Use a descriptive name for the node:
node.name: HappyNode
运行python代码后输出到控制台:
cluster.name: BLABLABLABLABLA
# Use a descriptive name for the node:
node.name: HEHEHEHEHEHEHE
我尝试将其添加到代码的底部以确保将其写入文件,如此处所述:[Matheus Portela's response],但我没有运气:
with open('elastic.yml', 'w') as f:
yaml.dump(data, f)
我收到以下错误:
data['cluster.name'] = 'BLABLABLABLABLA'
TypeError: 'NoneType' object does not support item assignment
答案 0 :(得分:2)
假设(未更改的)elastic.yml
是您的输入,则可以运行:
import ruamel.yaml
file_name = 'elastic.yml'
yaml = ruamel.yaml.YAML()
with open(file_name) as fp:
data = yaml.load(fp)
data['cluster.name'] = 'BLABLABLABLABLA'
data['node.name'] = 'HEHEHEHEHEHEHE'
with open(file_name, 'w') as fp:
yaml.dump(data, fp)
# display file
with open(file_name) as fp:
print(fp.read(), end='')
获得以下输出:
cluster.name: BLABLABLABLABLA
# Use a descriptive name for the node:
node.name: HEHEHEHEHEHEHE
由于程序显示了文件的内容,因此可以确定它已更改