,
package main
import (
"encoding/csv"
"fmt"
"os"
"strconv"
)
func main() {
outfile := "file.tsv"
f, err := os.Create(outfile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer f.Close()
w := csv.NewWriter(f)
defer w.Flush()
w.Comma = '\t'
a := []string{"a", "b"}
i, j := 0, 1
x := float64(2.7)
// Write row.
err = w.Write(
[]string{
a[i], a[j],
strconv.FormatFloat(x, 'f', 4, 64),
},
)
if err != nil {
fmt.Println(err)
}
}
Çıktı: Eğer goroutines kullanırsanız
$ cat file.tsv
a b 2.7000
$
, burada csv.Writer korumak için bir muteks'in kullanan bir versiyonu.
package main
import (
"encoding/csv"
"fmt"
"os"
"strconv"
"sync"
)
type csvWriter struct {
w *csv.Writer
m sync.Mutex
}
func (c *csvWriter) write(rec []string) error {
c.m.Lock()
defer c.m.Unlock()
return c.w.Write(rec)
}
func (c *csvWriter) flush() {
c.m.Lock()
defer c.m.Unlock()
c.w.Flush()
}
func main() {
outfile := "file.tsv"
f, err := os.Create(outfile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer f.Close()
w := csvWriter{w: csv.NewWriter(f)}
defer w.flush()
w.w.Comma = '\t'
a := []string{"a", "b"}
i, j := 0, 1
x := float64(2.7)
// Write row.
err = w.write(
[]string{
a[i], a[j],
strconv.FormatFloat(x, 'f', 4, 64),
},
)
if err != nil {
fmt.Println(err)
}
}
['tabwriter'] (https://golang.org/pkg/text/tabwriter/) paketine bakmalısınız. –