读操作
import (
"os"
"encoding/csv"
"bufio"
)
func ReadCSV(csvPath string, userCh chan []string, comma rune, hasFirstTitle bool, readNum int) {
f, err := os.Open(csvPath)
defer f.Close()
if err != nil {
return err
}
buf := bufio.NewReader(f)
r := csv.NewReader(buf)
if comma != 0 {
r.Comma = comma //'\t'
}
for i := 0; ; i++ {
if readNum > 0 && i == readNum {
break
}
record, err := r.Read()
//Reader实例的Read方法
//一般情况下返回字符数组和ErrFieldCount(用于判断每一行的列数是否都相同)
//否则返回的err为non-nil record或non-nil error
//没有数据返回io.EOF
if err == io.EOF {
break
}
if err != nil {
return err
}
if hasFirstTitle {
if i > 0 {
//处理数据
handle...
}
} else {
if i < readNum {
userCh <- record
}
}
}
}
网友评论