-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv.go
66 lines (55 loc) · 1.13 KB
/
csv.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package fs
import (
"bufio"
"encoding/csv"
"fmt"
"io"
"os"
io2 "github.com/breathbath/go_utils/v2/pkg/io"
)
func ReadCsvFile(filePath string, lineParser func(int, []string) error, lineSep rune, leastColumnsCount int) (err error) {
if !FileExists(filePath) {
err = fmt.Errorf("no file found at %s", filePath)
return
}
csvFile, err := os.Open(filePath)
if err != nil {
return
}
defer func() {
closeErr := csvFile.Close()
if closeErr != nil {
io2.OutputError(closeErr, "", "")
}
}()
fileReader := csv.NewReader(bufio.NewReader(csvFile))
fileReader.Comma = lineSep
lineNumber := 0
for {
lineNumber++
line, curErr := fileReader.Read()
if curErr == io.EOF {
break
} else if curErr != nil {
return fmt.Errorf(
"failed to parse csv file %s at line %d, reason: %s",
filePath,
lineNumber,
curErr.Error(),
)
}
if len(line) != leastColumnsCount {
return fmt.Errorf(
"unexpected columns count %d on line %d: expected count is %d",
len(line),
lineNumber,
leastColumnsCount,
)
}
err = lineParser(lineNumber, line)
if err != nil {
return
}
}
return nil
}