csv

最后更新于:2022-04-02 02:43:25

[TOC] ## 解析 csv ``` in := `first_name,last_name,username "Rob","Pike",rob Ken,Thompson,ken "Robert","Griesemer","gri" ` r := csv.NewReader(strings.NewReader(in)) //r.Comma = ';' // 指定分隔符 //r.Comment = '#' // 指定注释 for { record, err := r.Read() if err == io.EOF { break } if err != nil { log.Fatal(err) } fmt.Println(record) } // Output: // [first_name last_name username] // [Rob Pike rob] // [Ken Thompson ken] // [Robert Griesemer gri] ``` ## 数组转 csv ``` records := [][]string{ {"first_name", "last_name", "username"}, {"Rob", "Pike", "rob"}, {"Ken", "Thompson", "ken"}, {"Robert", "Griesemer", "gri"}, } w := csv.NewWriter(os.Stdout) w.WriteAll(records) // calls Flush internally if err := w.Error(); err != nil { log.Fatalln("error writing csv:", err) } ```
';