在GO中打印表的有效方法

2q5ifsrm  于 2023-02-01  发布在  Go
关注(0)|答案(3)|浏览(260)

我想知道一个简单有效的方法来打印一个表。我找到的解决方案工作,但它真的很难看。
谢谢!

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())
8tntrjer

8tntrjer1#

标准库中的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

p5cysglq

p5cysglq2#

例如,

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
$

如果你使用goroutine,这里有一个版本使用互斥锁来保护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)
    }
}
bvuwiixz

bvuwiixz3#

选择一个现有包可以简化你的代码,也可以增加代码的可维护性。试试go-pretty

+---------------------------------------------------------------------+
| Game of Thrones                                                     +
+-----+------------+-----------+--------+-----------------------------+
|   # | FIRST NAME | LAST NAME | SALARY |                             |
+-----+------------+-----------+--------+-----------------------------+
|   1 | Arya       | Stark     |   3000 |                             |
|  20 | Jon        | Snow      |   2000 | You know nothing, Jon Snow! |
| 300 | Tyrion     | Lannister |   5000 |                             |
+-----+------------+-----------+--------+-----------------------------+
|     |            | TOTAL     |  10000 |                             |
+-----+------------+-----------+--------+-----------------------------+

相关问题