-1

我对 PyYAML 很陌生,并不了解它的一切。我有一个带有列表的 YAML 文件;

the-list:
  - "string1"
  - "string2"
  - "string3"

我设法找出如何在我的 python 文件中获取列表,但不知道如何在其上添加另一个字符串,并将其保存到 YAML 文件中。所以它会变成

the-list:
  - "string1"
  - "string2"
  - "string3"
  - "newstring"

帮助表示赞赏!这是我用于读取 YAML 文件的代码:

with open('config.yml', 'r') as f:
    config = yaml.load(f)

LIST = config["the-list"]
4

1 回答 1

1

我在评论中给出了数据类型的线索list。只需append将新项目添加到列表中:

config["the-list"].append("newstring")
with file('config.yml', 'w') as f:
    yaml.dump(config, f) 
于 2014-05-17T14:59:55.353 回答