[英]Appending values of a key before spaces
我使用ruamel.yaml插入一些值,但它将值附加在空格之后而不是空格之前。 当前代码在行空格后附加值,如下面的YAML文件所示。 YAML输出标记**新值插入此处**
prefix_state:
v4:
8.8.8.8/32:
description: GOOGLE_DNS
enabled: true
tags:
- dns
community:
lb:
- SELF_NO_EXPORT
- TELCOM_NO_EXPORT
- BUSINESS_NO_EXPORT
**- <NEW VALUE INSERTED HERE>**
10.10.1.0/24:
description: SELF_LOCAL
enabled: True
tags:
- local
community:
lb:
- <NEW VALUE INSERTED HERE>
用于在yaml文件中追加值的代码如下:
yamldata=yaml.load(prefix_state_data,Loader=yaml.RoundTripLoader)
for arg in argv:
if arg is None:
pass
else:
for i in yamldata['prefix_state']['v4']:
if yamldata['prefix_state']['v4'][i]['community']['lb'] is not None:
yamldata['prefix_state']['v4'][i]['community']['lb'].append(arg+'_NO_EXPORT')
else:
yamldata['prefix_state']['v4'][i]['community']['lb']=[arg+'_NO_EXPORT']```
Expected end result is as below:
v4:
8.8.8.8/32:
description: GOOGLE_DNS
enabled: true
tags:
- dns
community:
lb:
- SELF_NO_EXPORT
- TELECOM_NO_EXPORT
- BUSINESS_NO_EXPORT
**- <NEW VALUE INSERTED HERE>**
10.10.1.0/24:
description: SELF_LOCAL
enabled: True
tags:
- local
community:
lb:
- <NEW VALUE INSERTED HERE>
在ruamel.yaml中,注释和空行与它们之前的元素相关联:如果它们遵循键值对,则它们与前面的键相关联,如果它们遵循序列,则它们与它们遵循的元素的索引相关联。
您似乎错误地认为您的“空”行是在序列之后,或者甚至在键8.8.8.8/32
和10.10.1.0/24
。 ruamel.yaml没有这样的概念,StackOverflow上的文档或答案都没有做出那种声明AFAIK(如果他们确实请指出你在哪里得到这个错误的信息)。
假设你有一个包含一行或多行注释的序列(并且空行被认为是没有首字母#的注释),在特定索引(可能是最后一项的索引,如你的情况)之后,你可以做两件事之一:
在包含注释的现有项之后插入一个新项,并移动注释(在最后一项之后插入与添加相同)
在原始位置之前插入旧项目,并使用新项目覆盖原始旧项目(现在是一个索引)。 注释/空行现在将与
由于第二个选项更容易实现,我将在此处使用它
import sys
import ruamel.yaml
arg = 'XXX'
yaml_str = """\
prefix_state:
v4:
8.8.8.8/32:
description: GOOGLE_DNS
enabled: true
tags:
- dns
community:
lb:
- SELF_NO_EXPORT
- TELCOM_NO_EXPORT
- BUSINESS_NO_EXPORT
10.10.1.0/24:
description: SELF_LOCAL
enabled: True
tags:
- local
community:
lb:
"""
yaml = ruamel.yaml.YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
data = yaml.load(yaml_str)
yd = data['prefix_state']['v4']
for i in yd:
if yd[i]['community']['lb'] is not None:
lb = yd[i]['community']['lb']
lb.insert(len(lb)-2, lb[len(lb)-1])
lb[-1] = arg + '_NO_EXPORT'
else:
yd[i]['community']['lb'] = [arg + '_NO_EXPORT']
yaml.dump(data, sys.stdout)
这使:
prefix_state:
v4:
8.8.8.8/32:
description: GOOGLE_DNS
enabled: true
tags:
- dns
community:
lb:
- SELF_NO_EXPORT
- BUSINESS_NO_EXPORT
- TELCOM_NO_EXPORT
- XXX_NO_EXPORT
10.10.1.0/24:
description: SELF_LOCAL
enabled: true
tags:
- local
community:
lb:
- XXX_NO_EXPORT
请注意,文件格式为YAML,包名称为ruamel.yaml
,自2006年以来,YAML文件的推荐扩展名为.yaml
。但最重要的是, YML与YAML一样古老,但格式完全不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.