2017-11-04 6 views
0

YAML 파일을 읽고 특정 값을 업데이트하는 함수를 작성해야합니다. YAML 파일은 사전으로 yaml 파일을 읽고 파이썬을 사용하여 값을 업데이트하는 방법

sample : 
    test_example: 
    parent: 
     attribute_1: 2 
     attribute_2: 2 
    parent2: 
     childList: 
     - group: 2 
      type: "test" 
      track_int: 
      - key_1: 3 
       key_2: 25 
       state: present 
      state: present 
     - group: 4 
      typr: "old" 
      track_int: 
      - key_1: 3 
       key_2: 25 
       state: present 
      state: present 

지금 내가 키를 전달하는 기능을 작성해야, 사전이며 특정 값 예에 대한 값을 교체해야합니다 - test_example["parent"]["attribute_2"]- 5

test_example["parent2"]["childList"][0]["group"] 4에 업데이트 및 업데이트

어떻게 할 수 있습니까?

+0

이 YAML 파일/문서는 사전이 아니며 매핑 및 시퀀스 (및 스칼라)의 조합입니다. 루트에는 Python 사전으로로드되는 매핑이 있지만 "YAML 파일은 [사전]입니다"라는 말은 잘못되었습니다. – Anthon

답변

0

당신이 "test""old"하고 다음 유일한 옵션은 ruamel.yaml (면책 조항을 사용하는 것입니다 시퀀스 들여 쓰기에 대시의 오프셋 (offset) 주위의 불필요한 따옴표를 포함하여 그대로 입력 파일의 나머지 부분을 보존하려면 : I

import sys 
import ruamel.yaml 

yaml = ruamel.yaml.YAML() 
yaml.preserve_quotes = True 
yaml.indent(mapping=4, sequence=4, offset=2) 

with open('input.yaml') as fp: 
    data = yaml.load(fp) 

test_example = data['sample'] 
test_example["parent2"]["childList"][0]["group"] =4 
test_example["parent"]["attribute_2"] = 5 
yaml.dump(data, sys.stdout) 

이 제공 : 파이썬 test_example

sample: 
    test_example: 
    parent: 
     attribute_1: 2 
     attribute_2: 5 
    parent2: 
     childList: 
      - group: 4 
      type: "test" 
      track_int: 
       - key_1: 3 
       key_2: 25 
       state: present 
      state: present 
      - group: 4 
      typr: "old" 
      track_int: 
       - key_1: 3 
       key_2: 25 
       state: present 
      state: present 

명명은 물론에 해당 할 수없는 패키지의 저자)입니다 입력 파일의. 그 문자는 None으로로드됩니다 (입력이 YAML 문서를 제시 할 때 실제로 들여 쓰기되었다고 가정).

관련 문제