【问题标题】:How to add a mapping in yaml file using python如何使用 python 在 yaml 文件中添加映射
【发布时间】:2021-11-11 03:07:30
【问题描述】:

我有一个下面的 yml 文件 samplelambda1.yml

Mappings:
  Environments:
    dev:
        DefaultLambdaConcurrency: '10'
    test:
        DefaultLambdaConcurrency: '10'
    staging:
        DefaultLambdaConcurrency: '10'
    production:
        DefaultLambdaConcurrency: '10'

我有多个文件,例如 samplelambda2,3,4....30

我需要在 python 脚本的帮助下为所有 yml 文件添加另一个映射,我们该怎么做?我尝试了字符串替换,但打开文件并替换多行是一项复杂的操作。

production-new:
    DefaultLambdaConcurrency: '10'

【问题讨论】:

  • 问题似乎是“如何在 Python 中正确处理 yaml 文件?”答案是没有内置的标准库支持,您最好使用第三方库而不是尝试自己编写它,因为它是一种标准格式,有很多已建立的支持(但还没有'还没有进入标准库)。对于 Stack Overflow 来说,这样的请求是无关紧要的。我建议你试试an internet search。这个should have been your first step anyway.

标签: python yaml mapping


【解决方案1】:

感谢@kaushal,下面的代码对我有用

对于多个文件,我在 for 循环中迭代代码

data={}

with open("test.yml") as ymlfile:
    data = yaml.load(ymlfile, Loader=yaml.FullLoader)
    print(data)

data['Mappings']['Environments']['production-new'] = {'DefaultLambdaConcurrency': '10'}

print(data)

with open("test.yml",'w') as ymlfile:
    dumpdata = yaml.dump(data)
    ymlfile.write(dumpdata)

【讨论】:

    【解决方案2】:

    这个问题没有表现出任何努力(没有冒犯,但 OP 应该尝试他的方法并在他卡住的地方发布)所以这只是提示。

    import os
    
    for filename in os.listdir(directory):
        // read each YAML using this: https://stackoverflow.com/a/1774043/5353128
        // add your key value in the read YAML dict.
        // Use yaml.dump() to save the content back to file.
    

    【讨论】:

    • 如果问题不符合标准,您应该对此发表评论并投票关闭它,而不是尝试回答。
    • @KarlKnechtel 我相信帮助人们而不是遵循“标准”。
    • 没关系,但是 Stack Overflow 存在,以后其他人可以搜索。它不是论坛
    • 有时你所需要的只是开始工作谢谢@Kaushal28
    • 但挑战在于 yaml 文件与 jinja 集成 yaml.j2 扩展和 yaml.load 可以读取任何想法我们如何解析与 jinja 集成的 yaml?
    【解决方案3】:

    您可以使用pyyaml 在 python 中处理 yaml 文件。要添加到现有的 yaml,您可以执行以下操作:

    import yaml
    
    with open("file_append.yaml", "r") as fs:
            append_dict = yaml.load(fs, Loader=yaml.SafeLoader)
    
    append_to = ["file_1.yaml"]
    
    for file_name in append_to:
        with open(file_name, "r") as fs:
                target_dict = yaml.load(fs, Loader=yaml.SafeLoader)
    
        target_dict["Mappings"]["Environments"] = {**target_dict["Mappings"]["Environments"], **append_dict}
    
        with open(file_name, "w") as fs:
                yaml.dump(target_dict, fs)
    

    输出:

    Mappings:
      Environments:
        dev:
          DefaultLambdaConcurrency: '10'
        production:
          DefaultLambdaConcurrency: '10'
        production-new:
          DefaultLambdaConcurrency: '10'
        staging:
          DefaultLambdaConcurrency: '10'
        test:
          DefaultLambdaConcurrency: '10'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多