1.read a csv file and output its data
package main
import (
"fmt"
"io"
"log"
"os"
"encoding/csv"
)
func main() {
fmt.Println("Enter file path to CSV: ")
var csvFile string
_, err := fmt.Scanln(&csvFile)
if err != nil {
log.Fatal("Cannot read input")
return
}
readCsv()
}
func readCsv() {
//准备读取文件
fileName := "data.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)
}
fmt.Println("\n---------------------------\n")
// 针对小文件,也可以一次性读取所有的文件。注意,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)
}
}
2.create a csv file with data
package main
import (
"encoding/csv"
"os"
)
func main() {
f, err := os.Create("data.csv")
if err != nil {
panic(err)
}
defer f.Close()
f.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM,避免使用Microsoft Excel打开乱码
writer := csv.NewWriter(f)
//method 1:按行写入
writer.Write([]string{"编号", "姓名", "年龄"})
writer.Write([]string{"1", "张三", "23"})
writer.Write([]string{"2", "李四", "24"})
writer.Write([]string{"3", "王五", "25"})
writer.Write([]string{"4", "赵六", "26"})
//method 2:
data := [][]string{
{"1", "中国", "23"},
{"2", "美国", "23"},
{"3", "bb", "23"},
{"4", "bb", "23"},
{"5", "bb", "23"},
}
w.WriteAll(data)//写入数据
writer.Flush() // 此时才会将缓冲区数据写入
}