1:新建csv_test.go文件。

package my_test_test

import (
    "bytes"
    "encoding/csv"
    "fmt"
    "os"
    "testing"
)

func TestA1(t *testing.T) {
    //从文件读csv
    readCsvFromFile()
    //从http返回的内容读取csv,这个场景是业务中可能拉取第三方api的数据
    readCsvFromByte()
}

//从byte读取csv数据
func readCsvFromByte() {
    str := `"sd","df","df"
"sv","ff","ggg"`
    dataByte := []byte(str)
    content, err := csv.NewReader(bytes.NewReader(dataByte)).ReadAll()
    if err != nil {
        fmt.Println(err)
        return
    }
    for k, row := range content {
        fmt.Println("k=", k)
        for _, row2 := range row {
            fmt.Println(row2)
        }
    }
}

//从文件读csv
func readCsvFromFile() {
    filePath := "E:\\Server\\go\\src\\any.com\\test\\my_test\\t.csv"
    file, err := os.Open(filePath)
    if err != nil {
        fmt.Println("err1", err)
        return
    }
    defer file.Close()
    //一次性读完文件内容
    content, err := csv.NewReader(file).ReadAll()
    if err != nil {
        fmt.Println("err2", err)
        return
    }
    for k, row := range content {
        fmt.Println("k=", k)
        for _, row2 := range row {
            fmt.Println(row2)
        }
    }
}