55 lines
1.3 KiB
Go
Executable File
55 lines
1.3 KiB
Go
Executable File
// Package csv provides utilities for loading and working with CSV data.
|
|
package csv
|
|
|
|
import (
|
|
"encoding/csv"
|
|
"io"
|
|
"os"
|
|
|
|
"git.sdf.org/jchenry/x"
|
|
osx "git.sdf.org/jchenry/x/os"
|
|
)
|
|
|
|
// CSV represents parsed CSV data with a header row and data rows.
|
|
type CSV struct {
|
|
// Header contains the column names from the first row
|
|
Header []string
|
|
// Data contains all remaining rows
|
|
Data [][]string
|
|
}
|
|
|
|
// LoadCSVFromFile loads CSV data from a file, treating the first row as a header.
|
|
// The file must not be nil or this function will panic.
|
|
// Returns the parsed CSV data or an error if reading fails.
|
|
func LoadCSVFromFile(f *os.File) (c *CSV, err error) {
|
|
x.Assert(f != nil, "LoadCSVFromFile: f is nil")
|
|
csvFile := osx.FileOrStdin(f)
|
|
defer csvFile.Close()
|
|
return LoadCSVFromReader(csvFile)
|
|
}
|
|
|
|
// LoadCSVFromReader loads CSV data from a reader, treating the first row as a header.
|
|
// The reader must not be nil or this function will panic.
|
|
// Returns the parsed CSV data or an error if reading fails.
|
|
func LoadCSVFromReader(r io.Reader) (c *CSV, err error) {
|
|
x.Assert(r != nil, "LoadCSVFromReader: r is nil")
|
|
reader := csv.NewReader(r)
|
|
|
|
header, err := reader.Read()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
data, err := reader.ReadAll()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
csvData := &CSV{
|
|
Header: header,
|
|
Data: data,
|
|
}
|
|
|
|
return csvData, nil
|
|
}
|