remove single quotes from dict values while adding

2019-08-02 20:17发布

I have an yaml file as mentioned below test1.yaml

resources:
  name:{get_param: vname}
  ssh_keypair: {get_param: ssh_keypair}

Now I want to add test1_routable_net: { get_param: abc_routable_net } under resources of test1.yaml Here is the code which I tried

import ruamel.yaml
yaml = ruamel.yaml.YAML()
test="{ get_param: abc_routable_net }".strip(‘\’’)
with open('/tmp/test1.yaml') as fp:
    data = yaml.load(fp)
data['resources'].update({‘test1_routable_net’:test})

yaml.dump(data,file('/tes2.yaml', 'w'))

output of above code is tes2.yaml

resources:
  name:{get_param: vname}
  ssh_keypair: {get_param: ssh_keypair}
  test1_routable_net: '{ get_param: abc_routable_net }'

Desired output is
tes2.yaml

resources:
  name:{get_param: vname}
  ssh_keypair: {get_param: ssh_keypair}
  test1_routable_net: { get_param: abc_routable_net }

I tried using test.strip('\'') , but no use still I see single quotes for the value .... How can I remove those quotes from the value?

2条回答
Fickle 薄情
2楼-- · 2019-08-02 20:24

In your program test is a string. Strings normally don't get quoted when dumped, but if their interpretation would be ambiguous, they will be. That is the reason why your output has the single quotes around them: to make sure that on reading back in this node is not incorrectly interpreted as a mapping instead of a string. Removing the non-existent quotes with .strip() therefore doesn't do anything.

You should work backwards from what you what you want to accomplish (you actually want a mapping instead of a string, as one can see from the output).

If you load your desired output, you will see that the value for test1_routable_net is a python dict (or a subclass thereof), so make sure that is what you assign to test:

import sys
import ruamel.yaml
yaml = ruamel.yaml.YAML()
test = { 'get_param': 'abc_routable_net' }
with open('./test1.yaml') as fp:
    data = yaml.load(fp)
data['resources'].update({'test1_routable_net': test})

yaml.dump(data, sys.stdout)

Which gives:

resources:
  name:{get_param: vname}
  ssh_keypair: {get_param: ssh_keypair}
  test1_routable_net:
    get_param: abc_routable_net

This is semantically the same as your desired output, but since you want the get_param: abc_routable_net in flow-style, you could add:

yaml.default_flow_style=None

to get your desired output. You can also look at assigning, to test, a ruamel.comments.CommentedMap, which gives you more fine grained control over its style (and comments, etc.).

查看更多
闹够了就滚
3楼-- · 2019-08-02 20:26

"test" is not a string it is a dict: example:

import ruamel.yaml
import yaml
yaml = ruamel.yaml.YAML()
test={ 'get_param': 'abc_routable_net' }
with open('test1.yaml') as fp:
    data = yaml.load(fp)

data['resources'].update({'test1_routable_net':test})
yaml.dump(data,open('test2.yaml', 'w'))
查看更多
登录 后发表回答