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'
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.
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).
No, YAML does not include any kind of "import" or "include" statement.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With