defaults:
adapter: postgres
host: localhost
development:
database: myapp_development
adapter: postgres
host: localhost
test:
database: myapp_test
adapter: postgres
host: localhost
In [1]:
import yaml
In [2]:
# read the yaml file into a dictionary
with open('input/file1.yaml', 'r') as fin:
info = yaml.load(fin)
In [3]:
# print the results
info
Out[3]:
In [4]:
# you can assign each section to a variable
defaults = info['defaults']
print(defaults)
In [5]:
# same as above
adapter = defaults['adapter']
print(adapter)
In [6]:
# change the value of a tag
defaults['adapter'] = 'mysql'
In [7]:
# write out the results to a file
with open('output/file1.yaml', 'w') as fin:
yaml.dump(info, fin)
In [10]:
print(info)
In [9]:
import ruamel.yaml
with open('input/file1.yaml', 'r') as fin:
inp = fin.read()
code = ruamel.yaml.load(inp, ruamel.yaml.RoundTripLoader)
code['defaults']['adapter'] = 'mysql'
print(ruamel.yaml.dump(code, Dumper=ruamel.yaml.RoundTripDumper), end='')
In [10]:
# write the yaml data to an output file
with open('output/file1_2.yaml', 'w') as fout:
fout.write(ruamel.yaml.dump(code, Dumper=ruamel.yaml.RoundTripDumper))
In [ ]: