golang reads csv file

golang读取csv文件的方法:先使用os.open()函数打开指定CSV文件,然后使用strings.Reader()方法即可读取CSV文件。

The method of reading CSV in go language:

package main

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

func main() {
    
    
	//准备读取文件
	filepath := "C:\\Users\\jancus\\Desktop\\asset.csv"
	GetBigCsvData(filepath)
	GetSmallCsvData(filepath)
}

func GetBigCsvData(filepath string) {
    
    
	file, err := os.Open(filepath)
	if err != nil {
    
    
		log.Fatalf("can not open the file, err is %+v", err)
	}
	defer file.Close()

	reader := csv.NewReader(file)
	//针对大文件,一行一行的读取文件
	for {
    
    
		row, err := reader.Read()
		if err != nil && err != io.EOF {
    
    
			log.Fatalf("can not read, err is %+v", err)
		}
		if err == io.EOF {
    
    
			break
		}
		fmt.Println(row)
	}
}

func GetSmallCsvData(filepath string) {
    
    
	//针对小文件,也可以一次性读取所有的文件
	//注意,r要重新赋值,因为ReadAll是读取剩下的
	file, err := os.Open(filepath)
	if err != nil {
    
    
		log.Fatalf("can not open the file, err is %+v", err)
	}
	defer file.Close()

	reader := csv.NewReader(file)
	content, err := reader.ReadAll()
	if err != nil {
    
    
		log.Fatalf("can not readall, err is %+v", err)
	}
	for _, row := range content {
    
    
		fmt.Println(row)
	}
}

The os package is a system standard library that contains operating system-related functions and variables. To open a file, you can use os.open.

Values ​​of the strings.Reader type (hereinafter referred to as Reader values) allow us to easily read the contents of a string. During the reading process, the Reader value saves the count of bytes read (hereinafter referred to as the read count).

The read count also represents the starting index position of the next read. Reader values ​​rely on such a count and slicing expressions for string values ​​to achieve fast reading.

Guess you like

Origin blog.csdn.net/SweetHeartHuaZai/article/details/130242820