• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1package filesystem
2
3import (
4	"bufio"
5	"encoding/csv"
6	"fmt"
7	"io"
8	"os"
9
10	"github.com/pkg/errors"
11)
12
13type lineHandler func(csvColumns []string)
14
15func GenerateCSVLines(filePath string, handler lineHandler) error {
16	csvFile, err := os.Open(filePath)
17	if err != nil {
18		return errors.Wrap(
19			err,
20			fmt.Sprintf("Could not open %s", filePath),
21		)
22	}
23	reader := csv.NewReader(
24		bufio.NewReader(csvFile),
25	)
26
27	isFirstLine := true
28	for {
29		line, err := reader.Read()
30		if err == io.EOF {
31			break
32		} else if err != nil {
33			return errors.Wrap(
34				err,
35				fmt.Sprintf("Could not read line from file %s", filePath),
36			)
37		}
38		if !isFirstLine {
39			handler(line)
40		}
41		isFirstLine = false
42	}
43	return nil
44}
45
46func WriteCSVToFile(headerCols []string, rowsOfCols [][]string, filepath string) error {
47	file, err := os.Create(filepath)
48	if err != nil {
49		return err
50	}
51	defer file.Close()
52
53	writer := csv.NewWriter(file)
54	defer writer.Flush()
55
56	if err := writer.Write(headerCols); err != nil {
57		return err
58	}
59	return writer.WriteAll(rowsOfCols)
60}
61