Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing tab separated values in Go

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.

like image 228
user3502035 Avatar asked Mar 03 '16 17:03

user3502035


1 Answers

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
}
like image 145
hauva69 Avatar answered Oct 05 '22 03:10

hauva69