mailinglabelmaker/csv.go

58 lines
1.1 KiB
Go

package main
import (
"encoding/csv"
"os"
)
type CSV struct {
index map[string]int
records [][]string
}
func LoadCSVFromFile(filename string) CSV {
f, err := os.Open(filename)
if err != nil {
panic(err)
}
r := csv.NewReader(f)
records, err := r.ReadAll()
index := make(map[string]int)
if err != nil {
panic(err)
}
for i := 0; i < len(records[0]); i++ {
index[records[0][i]] = i
}
csvo := CSV{index: index, records: records[1:]}
return csvo
}
func (this *CSV) NumRecords() int {
return len(this.records)
}
func (this *CSV) Record(index int) map[string]string {
ret := make(map[string]string)
for k, idx := range this.index {
ret[k] = this.records[index][idx]
}
return ret
}
func (this *CSV) GetField(index int, fieldLabel string) string {
return this.records[index][this.indexOfField(fieldLabel)]
}
func (this *CSV) PatreonEmptyAddress(index int) bool {
r := this.Record(index)
return r["Addressee"] == "" && r["Street"] == "" && r["City"] == "" && r["State"] == "" && r["Zip"] == "" && r["Country"] == ""
}
func (this *CSV) indexOfField(fieldLabel string) int {
return this.index[fieldLabel]
}