YAML Processing

Contents of input/file1.yaml

defaults:
  adapter:  postgres
  host:     localhost

development:
  database: myapp_development
  adapter:  postgres
  host:     localhost

test:
  database: myapp_test
  adapter:  postgres
  host:     localhost

Using the yaml library


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]:
{'defaults': {'adapter': 'postgres', 'host': 'localhost'},
 'development': {'adapter': 'postgres',
  'database': 'myapp_development',
  'host': 'localhost'},
 'test': {'adapter': 'postgres',
  'database': 'myapp_test',
  'host': 'localhost'}}

In [4]:
# you can assign each section to a variable
defaults = info['defaults']
print(defaults)


{'adapter': 'postgres', 'host': 'localhost'}

In [5]:
# same as above
adapter = defaults['adapter']
print(adapter)


postgres

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)


{'defaults': {'adapter': 'mysql', 'host': 'localhost'}, 'development': {'database': 'myapp_development', 'adapter': 'postgres', 'host': 'localhost'}, 'test': {'database': 'myapp_test', 'adapter': 'postgres', 'host': 'localhost'}}

Using ruamel.yaml


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='')


defaults:
  adapter: mysql
  host: localhost

development:
  database: myapp_development
  adapter: postgres
  host: localhost

test:
  database: myapp_test
  adapter: postgres
  host: localhost

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 [ ]: