0

I was trying to make a tool that updates yaml values in files that have "PENDING" in them. It does work, but I need it to be formatted like this:

fields:
  setName: ("name")
  WishName: ("name")
  WishNameState: ("PENDING")

However, it wants to dump it in this format:

fields: {WishName: ("name"), WishNameState: ("APPROVED"), setName: ("name")}

How can I make it dump in the format I want it to? Here's my code, so you know how I'm currently doing it:

import glob
import os
import yaml
def processFile(f,t):
    data = open(f,'rb').read()
    lines = data.replace('\r\n','\n').split('\n')
    lines_found = []
    for i,x in enumerate(lines):
        if t in x:
            lines_found.append(i+1)

    return lines_found

term = 'PENDING'
for x in glob.glob('*.yaml'):
    r = processFile(x,term)
    if r:
        with open(x) as f:
            yamlfile = yaml.load(f)

        fields = yamlfile['fields']
        name = fields['WishName']

        print('Name: ' + name)
        print('Approve or reject?')
        aor = raw_input('a/r: ')

        if aor == 'a':
            fields['setName'] = name
            fields['WishNameState'] = '("APPROVED")'
            with open(x, "w") as f:
                yaml.dump(yamlfile, f)
        elif aor == 'r':
            fields['WishNameState'] = '("REJECTED")'
            with open(x, "w") as f:
                yaml.dump(yamlfile, f)
        else:
            'Invalid response. Shutting down...'
            sys.exit()

print('End of results!')

Any and all help is appreciated! Thanks :)

Developre
  • 1
  • 7
  • Your code change yaml files as expected. What's wrong? – falsetru Jul 03 '16 at 01:53
  • 1
    A similar question, http://stackoverflow.com/a/18210750/5781248 – J.J. Hakala Jul 03 '16 at 01:58
  • @falsetru, the problem is I want it to be formatted a different way when it is dumped. It turns everything into a dict. I want the format to stay as `fields:(NEWLINE)setName: ("hey")(NEWLINE)` etc. However, it dumps it like `fields:{setName: ("Hey"), WishName: ("Hi")}` and I don't want it to do that. – Developre Jul 03 '16 at 02:15

1 Answers1

2

In your code, replace

yaml.dump(yamlfile, f)

with

yaml.dump(yamlfile, f, default_flow_style=False)

Jnana
  • 21
  • 3