gogofmt

Why does "fmt.Sprintf("%v,", lines[i])" put the comma on new line?


This is the full code:

files, _ := ioutil.ReadDir("files")
for _, f := range files {
    input, err := ioutil.ReadFile("files/" + f.Name())
    lines := strings.Split(string(input), "\n")

    for i, _ := range lines {
        lines[i] = fmt.Sprintf("%v,", lines[i])
    }

    output := strings.Join(lines, "\n")
    err = ioutil.WriteFile("files/"+f.Name()+"fix", []byte(output), 0644)
    if err != nil {
        log.Fatalln(err)
    }
}

I assume it is because lines[i] must contain a newline byte at the end of the string.. I have tried to remove it but failed..

The files I load are just json files e.g.

line 1: { "foo":"bar","baz":null }

line 2: { "foo":"bar","baz":"quz" }

Where I am trying to add a comma to the end of all lines.. any help would be much appreciated

Just to make myself a little more clear, what I get now is:

{ "foo":"bar","baz":null }
,
{ "foo":"bar","baz":"quz" }
,

whereas what I want to get is:

{ "foo":"bar","baz":null },
{ "foo":"bar","baz":"quz" },

Solution

  • Try trimming the line to clean up whatever trailing unicode code points it has:

    import "strings"
    
    // ...
    
    for _, line := range lines {
            line = fmt.Sprintf("%v,", strings.Trim(line, " \r\n"))
    }