Tan
Tan

Reputation: 47

Single quote appears after YAML dump

I have a problem that I wish to prevent single quote appearing in my YAML file. Is there anyway I can achieve the intended output where the goal is displayed without the single quote?

I have following code that I run in Python to update the file: (The format checking of the input is not implemented as this is a practice I'm doing to learn)

import sys
import yaml
import ruamel.yaml

def updateInformation():
    agentName = input("What is the name of agent you want to update?")
    endGoal = input("What is the new coordinate you want to update, type in terms of [x, y] where x and y are numbers")
    updateInputFile(agentName, endGoal)

def updateInputFile(agentName, endGoal):
    yaml = ruamel.yaml.YAML()
    i = 0
    with open('input.yaml') as f:
        doc = yaml.load(f)
    print(doc)
    for v in doc:
        if i < len(doc[v]):
            if doc['agents'][i]['name'] != agentName:
                i = i + 1
                pass
            else:
                if doc['agents'][i]['name'] == agentName:
                    doc['agents'][i].update({'goal': endGoal})
                    break

    yaml.representer.ignore_aliases = lambda *data: True
    with open('input.yaml', 'w') as f:
        yaml.dump(doc, f)

Currently the output file after the following code has been executed:

agents:
- start: [0, 0]
  goal: '[3, 1]'
  name: agent0
- start: [2, 0]
  goal: [0, 0]
  name: agent1
map:
  dimensions: [3, 3]
  obstacles:
  - !!python/tuple [0, 1]
  - !!python/tuple [2, 1]

Intended output:

agents:
- start: [0, 0]
  goal: [3, 1]
  name: agent0
- start: [2, 0]
  goal: [0, 0]
  name: agent1
map:
  dimensions: [3, 3]
  obstacles:
  - !!python/tuple [0, 1]
  - !!python/tuple [2, 1]

I'm thinking that it could be the possibility when it is being dumped back to YAML file, the value of endGoal faces an ambiguous interpretation as a string that results it being single quoted in the YAML file.

Upvotes: 1

Views: 550

Answers (1)

Rob Bricheno
Rob Bricheno

Reputation: 4653

endGoal is a string right after you input it.

Try making it into a list of int before updating the YAML:

endGoal = '[1,2]' # for example
endGoal = [int(a_string) for a_string in endGoal.strip('[]').split(',')]

Upvotes: 3

Related Questions