【问题标题】:PyYAML add string to listPyYAML 将字符串添加到列表
【发布时间】:2014-07-05 20:25:31
【问题描述】:

我对 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"]

【问题讨论】:

  • 介意分享你用来获取列表的代码吗?一旦列表在 python 中,它就会变成 list 并且可以修改,例如项目可能是appended。
  • 感谢您的编辑。关于我应该如何做到这一点的任何想法?

标签: python string list yaml pyyaml


【解决方案1】:

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

config["the-list"].append("newstring")
with file('config.yml', 'w') as f:
    yaml.dump(config, f) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 2011-09-10
    • 2018-08-12
    • 2022-07-28
    • 2011-12-15
    • 2023-02-15
    • 2015-07-31
    相关资源
    最近更新 更多