Home  >  Article  >  Backend Development  >  How to read csv file in golang

How to read csv file in golang

尚
Original
2019-12-31 10:18:577108browse

How to read csv file in golang

go语言读取CSV的方法:

package main
 
import (
    "encoding/csv"
    "fmt"
    "io"
    "log"
    "os"
)
 
func main() {
    //准备读取文件
    fileName := "D:\\gotest\\src\\source\\test.csv"
    fs, err := os.Open(fileName)
    if err != nil {
        log.Fatalf("can not open the file, err is %+v", err)
    }
    defer fs.Close()
 
    r := csv.NewReader(fs)
    //针对大文件,一行一行的读取文件
    for {
        row, err := r.Read()
        if err != nil && err != io.EOF {
            log.Fatalf("can not read, err is %+v", err)
        }
        if err == io.EOF {
            break
        }
        fmt.Println(row)
    }
 
    //针对小文件,也可以一次性读取所有的文件
    //注意,r要重新赋值,因为readall是读取剩下的
    fs1, _ := os.Open(fileName)
    r1 := csv.NewReader(fs1)
    content, err := r1.ReadAll()
    if err != nil {
        log.Fatalf("can not readall, err is %+v", err)
    }
    for _, row := range content {
        fmt.Println(row)
    }
 
}

os包是系统标准库里面有操作系统相关的函数和变量,打开一个文件可以使用os.open。

strings.Reader类型的值(以下简称Reader值)可以让我们很方便地读取一个字符串中的内容。在读取的过程中,Reader值会保存已读取的字节的计数(以下简称已读计数)。

已读计数也代表着下一次读取的起始索引位置。Reader值正是依靠这样一个计数,以及针对字符串值的切片表达式,从而实现快速读取。

更多golang知识请关注golang教程栏目。

The above is the detailed content of How to read csv file in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Does golang require ORM?Next article:Does golang require ORM?