【问题标题】:How to update the values of yaml file using python code如何使用 python 代码更新 yaml 文件的值
【发布时间】:2021-10-07 13:59:27
【问题描述】:

我的任务是更新 yaml 文件中的值。 yaml 文件被读入 'doc' 与 yaml 库具有以下 sysntax

    with open('createvol.yml') as f:
        doc = yaml.load(f)

打印(文档)看起来像这样。

[{'hosts': 'localhost', 'tasks': [{'register': 'result', 'test_lun': {'serial': 'P1234_K1', 'storageserial': '{{ storageserial }}', 'state': 'present', 'data': {'cap_compression': '{{ cap_compression | default(None) }}', 'storagepool': {'id': '{{ poolid | default(None) }}'}, 'name': '{{ name  | default(None) }}', 'vol': '{{ vol | default(None) }}', 'size': '{{ size | default(None) }}'}}}, {'debug': 'var=result'}], 'collections': ['company.storage'], 'name': 'Test Create vol', 'vars': [{'poolid': 200}, {'size': '7.3KB'}, {'storageserial': 111111}, {'name': 'test_vol_create'}, {'cap_compression': ['compression', 'deduplication']}], 'facts': False}]

这里我需要更新 'vars' 下的值,例如 poolid、size、storageserial、name 可能有人请帮助我了解如何解析文档内容并根据需要更新值的 python 逻辑。

【问题讨论】:

    标签: python json dictionary automation yaml


    【解决方案1】:

    我一直在寻找非常相似的东西。似乎没有办法更新 yaml 文件中的单个值(这就是我想要做的),而无需将孔数据解析到您的代码中,按照您的意愿对其进行转换,然后将所有数据加载回文件。

    但是在查看了您的问题的上下文之后,解析孔数据可能对您来说是一个有用的解决方案。所以这里是:

    首先,我建议您将文件扩展名改为.yaml,而不是.yml。我之前的研究指出.yml 与某些库不兼容,而.yaml 完全一样,但以后不应该给这种麻烦。

    *注意:您可以同时导入 yamlruamel 库。一旦你已经在使用yaml.load(),下面是你如何通过只使用 yaml.

    *注2:所有数据都在方括号[]内。在 python 中,这表示一个包含单个项目的列表(我看不出有一个列表的理由 单个项目),这会给您的 代码。我建议你删除第一个[ 和最后一个]

    尽管有注 2,我接下来带来的示例将您的“单项列表”考虑在内。让我们看看:

    您当前的doc 变量已经加载了createvol.yml 文件数据。

    所以这个:

    print(doc[0]['hosts']) #[0] is only necessary because your data is inside square brackets [] 
    

    将返回:

    localhost
    

    这意味着你可以运行这个:

    # print first value of 'vars' (index = 0)
    print("poolid is:")
    print(doc[0]['vars'][0]['poolid']) #the first [0] is only necessary because your data is inside []
    
    # change and print the second value of 'vars' (index = 1)
    doc[0]['vars'][1]['size'] = '007 KB' #again: [0] is only necessary because your data is inside []
    
    print("new size is:")
    print(doc[0]['vars'][1]) #the first [0] is only necessary because your data is inside []
    

    然后得到这个:

    poolid is:
    200
    new size is:
    {'size': '007 KB'}
    

    使用这个想法,您可以更新加载数据中的任何值。更改后,您可以使用write 模式打开文件:

    with open('createvol.yml', 'w') as f: #'w' stands for writing mode
            yaml.dump(doc, f)
    

    【讨论】:

      猜你喜欢
      • 2016-09-26
      • 2015-04-17
      • 2023-02-11
      • 2021-05-02
      • 2023-04-07
      • 2018-04-17
      • 2012-11-10
      • 2017-01-03
      • 1970-01-01
      相关资源
      最近更新 更多