[英]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.