yaml.dump正在倾向于dict,我不希望它这样做

时间:2016-07-03 01:46:22

标签: python pyyaml

我试图制作一个工具来更新文件中的yaml值,这些文件包含" PENDING"在他们中。它确实有效,但我需要将其格式化为:

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

但是,它希望以这种格式转储它:

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

如何以我想要的格式转储? 这是我的代码,所以你知道我目前是怎么做的:

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

感谢任何和所有帮助!谢谢:))

1 个答案:

答案 0 :(得分:0)

在您的代码中,替换

  

yaml.dump(yamlfile,f)

  

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