Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append data to YAML file

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'
like image 497
Qex Avatar asked Feb 06 '18 14:02

Qex


People also ask

How do you write to a YAML file in Python?

Open config.py and add the following lines of code just below the read_yaml method and above the main block of the file. In the write_yaml method, we open a file called toyaml. yml in write mode and use the YAML packages' dump method to write the YAML document to the file.

How do I edit a YAML file?

You can open a YAML file in any text editor, such as Microsoft Notepad (Windows) or Apple TextEdit (Mac). However, if you intend to edit a YAML file, you should open it using a source code editor, such as NotePad++ (Windows) or GitHub Atom (cross-platform).

Does YAML support imports?

No, YAML does not include any kind of "import" or "include" statement.


1 Answers

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"

like image 104
Nebulosar Avatar answered Sep 21 '22 10:09

Nebulosar