1

I'm having difficulty modifying a saved YAML file. I want to load it, add a property to the dict, and re-save it. This is what I've done... (Python 3.9.7)

# my_file.yaml

- id: 001
  name: Steve
  likes:
    - soccer
    - steak
- id: 002
  name: Mary
  likes:
    - tennis
    - ice cream
from ruamel.yaml import YAML

with open("my_file.yaml") as file:
  yaml = YAML()
  l = yaml.load(file)
l[0]["address"] = "123 Street"
with open("my_file_new.yaml", 'w') as f:
  yaml.dump(l, f)

output too long to include, but it is definitely not what I expected.

How do I get the original file with just one extra row added?

GlaceCelery
  • 921
  • 1
  • 13
  • 30

1 Answers1

1

You probably want to use a string as the first argument to open(), and you might not be doing that in the second invocation, as it is unclear from your code where your variable my_new_file is declared, and what it has an attribute .yaml.

Instead provide a string as first argument to open(), and while you are at it, always open YAML documents as binary ('rb' resp. 'wb'), or (preferably) use a pathlib.Path():

import pathlib
from ruamel.yaml import YAML
old_path = pathlib.Path('my_file.yaml')
new_path = pathlib.Path('my_file_new.yaml')

yaml = YAML()
with open('my_file.yaml') as file:
  l = yaml.load(file)
# replace the previous two lines with: l = yaml.load(l, old_path)

l[0]['address'] = '123 Street'
with open('my_file_new.yaml', 'wb') as f:
  yaml.dump(l, f)
# replace the previous two lines with: yaml.dump(l, new_path)

print(new_path.read_text())

which gives:

# my_file.yaml

- id: 001
  name: Steve
  likes:
  - soccer
  - steak
  address: 123 Street
- id: 002
  name: Mary
  likes:
  - tennis
  - ice cream
Anthon
  • 69,918
  • 32
  • 186
  • 246