简体   繁体   中英

How to indent lines when appending to existing yaml file with yaml.dump in python

I have the following yaml file that I am opening to append to:

stats:
  downloaded:
  - https://someurl.com

I want to append the following 2 blocks nested under stats:

  pushed_to:
  - https://anotherurl.com
  mappings:
    https://someurl.com: https://anotherurl.com

End result:

stats:
  downloaded:
  - https://someurl.com
pushed_to:
- https://anotherurl.com
mappings:
    https://someurl.com: https://anotherurl.com

Desired end result with both pushed_to and mappings nested under stats:

stats:
  downloaded:
  - https://someurl.com
  pushed_to:
  - https://anotherurl.com
  mappings:
    https://someurl.com: https://anotherurl.com

My shortened version of code:

with open(file_path, 'a') as fl:
    input_data = FINAL_RESULT
    yaml.dump(input_data, fl, indent=4, default_flow_style=False)

I tried option "indent=4" but it only indented the very last line from input_data when I expected it to indent every thing.

Not sure if needed, but below is some of the code used to build FINAL_RESULT. Similar code is used for adding the mappings section

FINAL_RESULT = {}  
pushed_to = []  
pushed_to.append(object_url)
FINAL_RESULT['pushed_to'] = pushed_to

I reworked this and got it looking as desired.

Rather than appending to original, I read original yaml and stripped downloaded section out and added at top of FINAL_RESULT. Remaining logic building FINAL_RESULT remained unchanged. Then I tweaked my yaml open section to the below

    with open(file_path, 'w') as fl:
        input_data = {'stats': FINAL_RESULT}
        yaml.dump(input_data, fl, default_flow_style=False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM