我如何在 python 中编辑 yaml 文件

How I can edit yaml file in python

我要编辑yaml文件

params:
  test
description: |
  bla bla bla
  bla name2
  bla bla

params后面的名字,我可以用那个改

  with open("config.yml", 'r') as ymlfile:
    cfg = yaml.load(ymlfile)

cfg['params'] = 'lolilol'

with open('config.yml', 'w') as f:
        yaml.dump(cfg, f)

但是我想改一下描述里面的name2,请问怎么改,请

您可以简单地替换 name,但它会替换所有 name

import yaml
with open("demo.yml", 'r') as ymlfile:
    cfg = yaml.load(ymlfile)

cfg['params'] = 'lolilol'

# replace will replace all `name's` the it will found, if you want for example to 
# replace only first word you can use `replace('name', 'new_name', 1)`
cfg['description'] = cfg['description'].replace('name', 'new_name')
print(cfg)

输出

{'params': 'lolilol', 
 'description': 'bla bla bla
                 bla new_name
                 bla bla'}

更新

如果你想更新名字2

search_word = 'name2'
words = cfg['description'].split()
new_word = 'NAME'

if search_word in words:
    words[words.index(search_word)] = new_word

cfg['desciption'] = words
print(cfg)

输出

{'params': 'lolilol', 'description': ['bla', 'bla', 'bla', 'bla', 'NAME', 'bla', 'bla', 'name2']}

如果要更新所有name2 founded

search_word = 'name2'
words = cfg['description'].split()
new_word = 'NAME'

for i, word in enumerate(words):
    if word == search_word:
        words[i] = new_word

cfg['description'] = words

print(cfg['description'])

输出

{'params': 'lolilol', 'description': ['bla', 'bla', 'bla', 'bla', 'NAME', 'bla', 'bla', 'NAME']}