How do I append to a YAML file with python

后端 未结 1 1209
北海茫月
北海茫月 2021-01-29 01:19

I have a YAML file called data.yaml:

---
\'001\':
  name: Ben
  email: ben@test.com

I would like to have an updated file that loo

相关标签:
1条回答
  • You can, in general, not add to a YAML document in a file by just writing extra information at the end of that file. This migth work for YAML documents that have a mapping or sequence at the top level that is block style, but even then simply appending can only work for certain cases of documents.

    It is easy to just load your YAML to Python datastructure, update/extend that structure and then dump it back. That way you don't have to deal with potential duplicate keys, non-bare documents and other issues that will result in invalid YAML when you use simple appending. Assumping your original file is called input.yaml, the following does the trick:

    import sys
    from pathlib import Path
    import ruamel.yaml
    
    file_name = Path('input.yaml')
    
    record_to_add = dict(name='Lisa', email='lisa@test.com', numbers=['000-111-2222', '000-111-2223'])
    
    yaml = ruamel.yaml.YAML()
    yaml.explicit_start = True
    data = yaml.load(file_name)
    data['002'] = record_to_add
    yaml.dump(data, sys.stdout)
    

    which gives:

    ---
    '001':
      name: Ben
      email: ben@test.com
    '002':
      name: Lisa
      email: lisa@test.com
      numbers:
      - 000-111-2222
      - 000-111-2223
    
    0 讨论(0)
提交回复
热议问题