11

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.

user3502035
  • 263
  • 1
  • 3
  • 7
  • 6
    Have you read the documentation for the tabwriter package ? Its stated purpose is explicitely to write aligned text using whitespaces. You probably want to use the `csv` package instead (https://golang.org/pkg/encoding/csv/#Writer). – SirDarius Mar 03 '16 at 17:39

1 Answers1

17

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
}
hauva69
  • 171
  • 1
  • 7
  • 1
    csv writer is not a right choice to write tsv file because the writer wraps fields in double quotes "" when the field value contains ". There doesn't seem to be an option to turn off this wrapping in the csv module. – Kenji Noguchi Oct 06 '18 at 00:04
  • Havent tested it. but won't setting `LazyQuotes` to true would fix this? – aitchkhan Oct 12 '18 at 18:33
  • @aitchkhan don't think so: (type *csv.Writer has no field or method LazyQuotes) – dahui Mar 24 '22 at 16:34