我如何在python中编辑yaml文件

时间:2018-07-11 13:55:18

标签: python file yaml edit

我要编辑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)

但是我想更改一下descirption内的name2,我该怎么做,plz

1 个答案:

答案 0 :(得分:0)

您可以简单地替换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

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']}