Pyyaml - Python , omit !!int

51 views Asked by At

Is there a way to remove !!int after dumping to a yaml file?

Current output:

  • "cores": !!int "4" "disks": !!int "200"

Expected:

  • "cores": "4" "disks": "200"

Code:

Server = namedtuple("Server", "name ip mask gw vlan template cores sockets memory disks")
servers = []
for val in sheet.iter_rows(min_row=2,min_col=2, values_only=True):
    server = Server(val[1],val[2],val[3],val[4],val[5],val[6],val[7],val[8],val[9],val[10])
    servers.append(server._asdict())

vms_spec = {}
vms_spec['vms'] = servers

with open('test.yml','w') as yamlW:
    yaml.safe_dump(vms_spec,yamlW,indent=2,default_style='"')
1

There are 1 answers

1
Anthon On BEST ANSWER

You get the !!int because you are dumping integers but force the output to be all double quoted scalars. Without that, a YAML parser reading the output would think it would need to load a string.

With that knowledge the easy solution is to walk over the values and convert them to a string before dumping:

servers.append({k, str(v) for k, v in server._asdict().items())

Please note that the officially recommended extension for files containing YAML documents has been .yaml since at least September 2006.