登录
首页 >  Golang >  Go问答

使用 Go 语言从 CSV 文件中读取数据

来源:stackoverflow

时间:2024-03-25 23:54:29 234浏览 收藏

本文介绍了如何使用 Go 语言从 CSV 文件中读取数据。文章展示了一种通过索引获取数据的方法,并解释了如何使用标头名称而不是索引来获取特定数据。它提供了一个代码示例,展示了如何创建标题名称到列索引的映射,并在循环数据记录之前检查文件是否包含所需的列。

问题内容

正如您在下面看到的,我已经读取了 csv 文件并使用索引获取了数据。之后,我将标头名称与其各自的索引对齐。

现在,如何使用标头名称而不是索引从 csv 文件中获取特定数据?我是 golang 和编程新手。

func main() {
    file, ferr := os.Open("company1.csv")
    if ferr != nil {
    panic(ferr)
    }
    reader := csv.NewReader(file)
    reader.Comma = '|'
    reader.Comma = ','
    records, _ := reader.ReadAll()

    fmt.Println(records) // prints all the records
    fmt.Println("\n",records[1][0]) //to print the first record
    fmt.Println("\n",records[0]) // header
    //to print the index along the header
    index := 0
    for _, x := range records[0] {
    fmt.Println("\n",x ,"-",index)
    index++
    }

正确答案


创建从标题名称到列索引的映射。索引记录时使用该映射:

fields := make(map[string]int)
for i, name := range records[0] {
    fields[name] = i
}

for _, record = range records[1:] {
    x = record[fields["name"]]
    fmt.println(x)
}

上面的代码不处理文件中缺少预期列的情况。在循环数据记录之前添加此检查:

for _, name := range []string{"name", "column2"} {
    if _, ok := fields[name]; !ok {
        log.Fatal("field missing", name)
    }
}

本篇关于《使用 Go 语言从 CSV 文件中读取数据》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>