dqwmhrxt68679
2016-06-18 21:30
浏览 48
已采纳

将数组转换为csv

I have an array of different values - is there a way to convert it to csv string and output it via fmt.Print to stdout, without writing the csv to some file?

As far as I know, if I create a csv writer, I have to pass io file as a parameter, is there a way to just output it?

图片转代码服务由CSDN问答提供 功能建议

我有一个不同值的数组-有没有办法将其转换为csv字符串并通过 fmt.Print 到stdout,而无需将csv写入某些文件?

据我所知,如果创建csv编写器,我必须将io文件作为 参数,有没有办法输出它?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douyouzheng2209 2016-06-18 21:36
    已采纳

    Use os.Stdout as your io.Writer.

    点赞 评论
  • douw92892 2016-06-18 21:41

    yes:
    for string slice:

    package main
    
    import "encoding/csv"
    import "os"
    
    func main() {
        wr := csv.NewWriter(os.Stdout)
        wr.Write([]string{"test1", "test2", "test3"})
        wr.Flush()
    }
    

    for int (or any slice):

    package main
    
    import (
        "encoding/csv"
        "fmt"
        "os"
        "strings"
    )
    
    func main() {
        A := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} // []string{"test1", "test2", "test3"}
        st := strings.Fields(strings.Trim(fmt.Sprint(A), "[]"))
        wr := csv.NewWriter(os.Stdout)
        wr.Write(st)
        wr.Flush() // 0,1,2,3,4,5,6,7,8,9
    }
    

    another way:

    package main
    
    import (
        //"encoding/csv"
        "fmt"
        "strings"
    )
    
    func main() {
        A := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
        st := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(A)), ", "), "[]")
        fmt.Println(st) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
    }
    

    if your data is not int convert it to slice of string, then use strings.Join function.

    and see:
    go / golang: one-liner to transform []int into string

    点赞 评论

相关推荐 更多相似问题