我想知道在GO中打印表格的简单有效方法。我找到的解决方案有效,但实在太难看了。
很多坦克!outfile := "file.tsv"
f, err := os.Create(outfile)var buffer bytes.Buffer
buffer.WriteString(a[i])
buffer.WriteString("\t")
buffer.WriteString(a[j])
buffer.WriteString("\t")
buffer.WriteString(strconv.FormatFloat(x, 'f', 4, 64))
buffer.WriteString("\n")
// // write results to outfile
f.WriteString(buffer.String())
答案 0 :(得分:3)
例如,
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)
}
}
答案 1 :(得分:2)
对于这种情况,标准库中的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
您可以用任何io.Writer
替换os.Stdout。