在Go语言中编写制表符分隔的值(tab separated values),

huangapple go评论77阅读模式
英文:

Writing tab separated values in Go

问题

我正在尝试使用Go语言中的tabwriter包将制表符分隔的值写入文件。

records := map[string][]string{}
file, err := os.OpenFile(some_file, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
    log.Println(err)
}
w := new(tabwriter.Writer)
w.Init(file, 0, 4, 0, '\t', 0)
for _, v := range records {
    fmt.Fprintln(w, v[0], "\t", v[1], "\t", v[2], "\t", v[3])
    w.Flush()
}

我遇到的问题是写入文件的记录前面有两个额外的空格。我添加了调试标志,文件中的内容如下:

fname1  | mname1  | lname1      | age1
fname2  | mname2  | lname2      | age2

我无法确定问题出在哪里。感谢任何帮助。

英文:

I'm trying to write tab separated values in a file using the tabwriter package in Go.

records map[string] []string
file, err := os.OpenFile(some_file,  os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
    log.Println(err)
}
w := new(tabwriter.Writer)
w.Init(file, 0, 4, 0, '\t', 0)
for _, v := range records {
    fmt.Fprintln(w, v[0],"\t",v[1],"\t",v[2],"\t",v[3])
	w.Flush()
}

The problem I'm facing is that the records written to the file have two additional spaces prepended to them. I added the debug flag and this is what I get in the file:

fname1  | mname1  | lname1      | age1
fname2  | mname2  | lname2      | age2

I'm unable to see where I'm going wrong. Any help is appreciated.

答案1

得分: 17

根据SirDarius的建议,确实可以使用encoding/csv库来实现。你只需要将逗号(Comma)设置为水平制表符(horizontal tab),而不是默认的逗号。

package tabulatorseparatedvalues

import (
    "encoding/csv"
    "io"
)

func NewWriter(w io.Writer) (writer *csv.Writer) {
    writer = csv.NewWriter(w)
    writer.Comma = '\t'

    return
}
英文:

As SirDarius suggested encoding/csv is indeed the right choice. All you have to do is to set the Comma to a horizontal tab instead of the default value, which unsurprisingly is comma.

package tabulatorseparatedvalues

import (
    "encoding/csv"
    "io"
)

func NewWriter(w io.Writer) (writer *csv.Writer) {
    writer = csv.NewWriter(w)
    writer.Comma = '\t'

    return
}

huangapple
  • 本文由 发表于 2016年3月4日 01:28:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/35778958.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定