在 Go 中加载 CSV 文件

这是在 Go 中逐行打开 CSV 文件的一种非常简单的方法。假设我们有一个pops.csv看起来像这样的 CSV 文件

城市 人口
拉各斯 21000000
东京 37400000
德里 28500000
里约热内卢 13300000

要逐行读取文件,

package main

import (
    "encoding/csv"
    "fmt"
    "io"
    "os"
)

type CityPopulation struct {
    City  string
    Population string
}

func check(e error) {
    if e != nil {
        panic(e)
    }

}

func main() {
    fmt.Println("This is the entry point!")

    file, err := os.Open("pops.csv")
    check(err)
    println("Log: Opened CSV file")

    reader := csv.NewReader(file)

    var pops []CityPopulation

    for {
        line, err := reader.Read()

        if err == io.EOF {
            break
        }
        check(err)

        pops = append(pops, CityPopulation{
            City:  line[0],
            Population: line[1],
        })
    }
    for i := range pops {
        fmt.Printf("The city of %s is populated with %s people.\n" , pops[i].City, pops[i].Population)
    }
}

我们创建了一个结构CityPopulation来保存 CSV 的值。然后我们创建了一个函数check(e error)来检查错误。该函数仅检查文件中的错误和恐慌。

在 main 函数中,我们使用os.Open("pops.csv")打开 CSV 文件并加载它。然后我们用它csv.NewReader()来创建一个阅读器。然后我们使用 for 循环逐行读取文件。请注意io.EOF,当它到达 CSV 文件的末尾时,它由 reader.Read() 发出。然后我们将该行的内容加载到pops之前创建的切片中。