Golang 如何读取CSV文件
Golang提供了一个庞大的内置库,可用于执行文件的读写操作。要读取CSV文件,在Golang中使用以下方法:
- os.Open(): os.Open()方法打开指定的文件以进行读取。该方法返回的是os.File指针或错误。
- encoding/csv: 该包提供一个NewReader函数,用于读取CSV文件,并返回一个csv.Reader指针,进而用于将文件内容作为一系列记录进行读取。
注意: 使用离线编译器可获得更好的结果。将程序文件保存为.go扩展名。使用下面的命令来执行程序:
示例1: 假设CSV文件名为Students.csv,并且文件中的内容如下:
S001,Thomas Hardy,CS01
S002,Christina Berglund,CS05
S003,Yang Wang,CS01
S004,Aria Cruz,CS05
S005,Hanna Moos,CS01
下面是读取CSV文件的Golang程序:
// Go程序,说明如何
// 读取CSV文件
package main
import (
"encoding/csv"
"fmt"
"log"
"os"
)
func main() {
// os.Open()以只读模式打开指定文件,返回类型为os.File指针
file, err := os.Open("Students.csv")
// 检查错误
if err != nil {
log.Fatal("错误文件读取中", err)
}
// 关闭文件
defer file.Close()
// 调用csv.NewReader()函数
// 并将类型为os.File的对象作为其参数传递
// 这将创建一个新的csv.Reader来读取该文件
reader := csv.NewReader(file)
// ReadAll 读取CSV文件的所有记录
// 并将它们作为 string 切片的切片 返
// 后,并带有任何错误
records, err := reader.ReadAll()
// 检查错误
if err != nil
{
fmt.Println("读取记录时出错")
}
// 循环迭代,遍历并打印每个字符串切片
for _, eachrecord := range records
{
fmt.Println(eachrecord)
}
}
输出:
图1.1
可以在csv.Reader结构中定义自定义分隔符来读取CSV文件而不是逗号(,)。
NewReader函数返回的Reader结构
type Reader struct{
// Comma是由NewReader设置为(,)的字段分隔符
// 它可以被更改为自定义分隔符
// 但它必须是一个有效的符文,并且它不应该是\r、\n或Unicode替换字符(0xFFFD)。
Comma 符文
Comment 符文
FieldsPerRecord int
LazyQuotes bool
TrimLeadingSpace bool
ReuseRecord bool
TrailingComma bool
}
例子2: 下面的例子演示了如何读取具有自定义分隔符的CSV文件。假设CSV文件名为Sample.csv,文件中的内容如下:
Word1-Word2
Word3-Word4
Word5-Word6
下面是读取具有自定义分隔符的CSV文件的Golang程序:
// Golang program to illustrate
// How to read a csv file with
// custom separator
package main
import (
"encoding/csv"
"fmt"
"log"
"os"
)
func main() {
// os.Open() opens specific file in
// read-only mode and this return
// a pointer of type os.File
file, err := os.Open("Sample.csv")
// Checks for the error
if err != nil {
log.Fatal("Error while reading the file", err)
}
// Closes the file
defer file.Close()
// The csv.NewReader() function is called in
// which the object os.File passed as its parameter
// and this creates a new csv.Reader that reads
// from the file
reader := csv.NewReader(file)
// To specify the custom separator use the
// following syntax
// Comma is the field delimiter. By default it is
// set to comma (',') by NewReader.
// Comma must be a valid rune (int32) and must not be
// \r, \n, or the Unicode replacement character (0xFFFD).
reader.Comma = '-'
// ReadAll reads all the records from the CSV file and
// Returns them as slice of slices of string and an
// error if any
records, err := reader.ReadAll()
// Checks for the error
if err != nil
{
fmt.Println("Error reading records")
}
// Loop to iterate through
// and print each of the string slice
for _, eachrecord := range records
{
fmt.Println(eachrecord)
}
}
输出:
图1.2