doujia1904 2017-03-05 14:10
浏览 109
已采纳

转到:为什么“ fmt.Sprintf(”%v,”,lines [i])”将逗号放在新行上?

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), "
")

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

    output := strings.Join(lines, "
")
    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" },
  • 写回答

2条回答 默认 最新

  • dongsunny1113 2017-03-05 16:19
    关注

    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, " 
    "))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置