How to append data to YAML file

Qex picture Qex · Feb 6, 2018 · Viewed 16.8k times · Source

I have a file *.yaml with contents as below:

bugs_tree:
  bug_1:
    html_arch: filepath
    moved_by: user1
    moved_date: '2018-01-30'
    sfx_id: '1'

I want to add a new child element to this file under the node [bugs_tree] I have tried to do this as below:

if __name__ == "__main__":
    new_yaml_data_dict = {
        'bug_2': {
            'sfx_id': '2', 
            'moved_by': 'user2', 
            'moved_date': '2018-01-30', 
            'html_arch': 'filepath'
        }
    }

    with open('bugs.yaml','r') as yamlfile:
        cur_yaml = yaml.load(yamlfile)
        cur_yaml.extend(new_yaml_data_dict)
        print(cur_yaml)

Then file should looks that:

bugs_tree:
  bug_1:
    html_arch: filepath
    moved_by: username
    moved_date: '2018-01-30'
    sfx_id: '1234'
  bug_2:
    html_arch: filepath
    moved_by: user2
    moved_date: '2018-01-30'
    sfx_id: '2'

When I'm trying to perform .append() OR .extend() OR .insert() then getting error

cur_yaml.extend(new_yaml_data_dict)
AttributeError: 'dict' object has no attribute 'extend'

Answer

Nebulosar picture Nebulosar · Apr 10, 2018

If you want to update the file, a read isn't enough. You need to also write again against the file. Something like this would work:

with open('bugs.yaml','r') as yamlfile:
    cur_yaml = yaml.safe_load(yamlfile) # Note the safe_load
    cur_yaml['bugs_tree'].update(new_yaml_data_dict)

if cur_yaml:
    with open('bugs.yaml','w') as yamlfile:
        yaml.safe_dump(cur_yaml, yamlfile) # Also note the safe_dump

I didn't test this, but he idea is that you use a read to read the file and write to write to the file. Use safe_load and safe_dump like Anthon said:

"There is absolutely no need to use load(), which is documented to be unsafe. Use safe_load() instead"