-
Notifications
You must be signed in to change notification settings - Fork 3
/
csv.go
97 lines (82 loc) · 1.78 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"encoding/csv"
"os"
)
// CSVHandler handles input and output csv files
type CSVHandler struct {
*csv.Reader
fpRead *os.File
rHeader []string
lineNo int
*csv.Writer
wHeader []string
fpWrite *os.File
}
// Close closes file pointer of input and output csv files
func (c *CSVHandler) Close() {
c.fpRead.Close()
c.fpWrite.Close()
}
// NewCSVHandler returns initialized *CSVHandler
func NewCSVHandler(in, out string) (*CSVHandler, error) {
r, err := os.Open(in)
if err != nil {
return nil, err
}
w, err := os.Create(out)
if err != nil {
return nil, err
}
c := &CSVHandler{
fpRead: r,
fpWrite: w,
Reader: csv.NewReader(r),
Writer: csv.NewWriter(w),
}
// set header
c.rHeader, err = c.Read()
if err != nil {
return nil, err
}
return c, nil
}
// GetPosition returns position(read line number)
func (c *CSVHandler) GetPosition() int {
return c.lineNo
}
// Read returns []string and count up current position
func (c *CSVHandler) Read() ([]string, error) {
line, err := c.Reader.Read()
if err != nil {
return nil, err
}
c.lineNo++
return line, nil
}
// ReadMapItems reads lines from input csv file nad create map item, which has key=<header column name> val=<the value of the line>
func (c *CSVHandler) ReadMapItems(size int) ([]map[string]interface{}, error) {
items := make([]map[string]interface{}, 0, size)
header := c.rHeader
for i := 0; i < size; i++ {
line, err := c.Read()
if err != nil {
return items, err
}
item := make(map[string]interface{})
for j, key := range header {
item[key] = line[j]
}
items = append(items, item)
}
return items, nil
}
// Write writes a line into file
func (c *CSVHandler) Write(line []string) error {
err := c.Writer.Write(line)
if err != nil {
return err
}
c.Flush()
return nil
}