-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv_reader.go
52 lines (41 loc) · 1.13 KB
/
csv_reader.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
package main
import (
"encoding/csv"
"fmt"
"os"
)
// Reads all the contents of the provided CSV file into a [][]string value.
func readAllCSV(fileName string, path string) ([][]string, error) {
var file, err = os.Open(fmt.Sprintf("%s%s%s", path, string(os.PathSeparator), fileName))
if err != nil {
return nil, err
}
var reader = csv.NewReader(file)
records, err := reader.ReadAll()
if err != nil {
return nil, err
}
err = file.Close()
if err != nil {
return nil, err
}
return records, nil
}
// Reads the headers (first row) of the provided CSV into a []string value.
func readHeadersCSV(fileName string, path string) ([]string, error) {
var file, err = os.Open(fmt.Sprintf("%s%s%s", path, string(os.PathSeparator), fileName))
if err != nil {
return nil, err
}
var reader = csv.NewReader(file)
// When Read() is called on a particular reader, it reads a single line, reading the next line each time it is called. Hence, if called only once, it gets only the first row.
headers, err := reader.Read()
if err != nil {
return nil, err
}
err = file.Close()
if err != nil {
return nil, err
}
return headers, nil
}