2 回答
TA贡献1868条经验 获得超4个赞
tabwriter标准库中的包对于这种事情简单易行:
w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
fmt.Fprintln(w, "a\tb\tc\td\t")
fmt.Fprintln(w, "aa\tbb\tcc\t")
fmt.Fprintln(w, "aaa\tbbb\tccc\t")
fmt.Fprintln(w, "aaaa\tbbbb\tcccc\tdddd\t")
w.Flush()
// Prints out:
// a b c d
// aa bb cc
// aaa bbb ccc
// aaaa bbbb cccc dddd
您可以将 os.Stdout 替换为任何io.Writer.
TA贡献1859条经验 获得超6个赞
例如,
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)
}
}
输出:
$ cat file.tsv
a b 2.7000
$
如果您使用 goroutines,这里有一个使用互斥锁来保护 csv.Writer 的版本。
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)
}
}
- 2 回答
- 0 关注
- 447 浏览
添加回答
举报