Go Playbook

Course › Week 3 · Real data and speed › Day 2 · lesson 16 of 42 · 25 min reading + 60 min practice

Streaming CSV

Read a huge CSV one row at a time, and report bad rows instead of stopping.

encoding/csvio.Readerbufioerror reports

On this page
  1. The sample
  2. Reading
  3. Bad rows
  4. Writing
  5. Coming from PHP
  6. Practice
  7. Remember

Survey exports, booking imports, bank statements: CSV is where real data arrives, and it is never clean. A row with a missing column, a score written as a word, a comment with a comma and a line break inside quotes, and an invisible character at the start of the file that Excel put there.

Today: reading CSV one record at a time with encoding/csv, the header, rows that are wrong in shape and rows that are wrong in content, both reported with their line numbers, and writing CSV.

The sample

Every program on this page reads this responses.csv: answers to a course evaluation, one row per answer. Lines 4, 5 and 8 have a problem each, and the comment that starts on line 6 has a line break inside its quotes.

responses.csv
evaluation_id,question_id,score,comment
9001,q1,5,Clear explanations
9001,q2,4,"Good pace, but the room was cold"
9002,q1,3
9002,q2,six,Fine
9003,q1,2,"Too fast.
Could not take notes."
9003,q2,"4"x,ok
9004,q1,4,

Reading

1. One record at a time

csv.NewReader wraps any io.Reader, here an open file. Each Read returns the next record as a []string, until the error is io.EOF: the end of the file.

main.go
package main

import (
	"encoding/csv"
	"errors"
	"fmt"
	"io"
	"os"
)

func main() {
	file, err := os.Open("responses.csv")
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer file.Close()

	reader := csv.NewReader(file)
	for {
		record, err := reader.Read()
		if errors.Is(err, io.EOF) {
			break
		}
		fmt.Printf("%q  err=%v\n", record, err)
	}
}
$ go run .
["evaluation_id" "question_id" "score" "comment"]  err=<nil>
["9001" "q1" "5" "Clear explanations"]  err=<nil>
["9001" "q2" "4" "Good pace, but the room was cold"]  err=<nil>
["9002" "q1" "3"]  err=record on line 4: wrong number of fields
["9002" "q2" "six" "Fine"]  err=<nil>
["9003" "q1" "2" "Too fast.\nCould not take notes."]  err=<nil>
["9003" "q2"]  err=parse error on line 8, column 11: extraneous or missing " in quoted-field
["9004" "q1" "4" ""]  err=<nil>

%q on a slice quotes every element, so empty fields and line breaks are visible. The quoted comment on row 6 is one field with a newline inside: the reader handles CSV quoting for you, which splitting lines on commas never does.

Like bufio.Scanner (the logstat build day), the reader holds one record at a time, so a 2 GB file uses as little memory as a 2 KB one. Rows with problems still came back, with an error next to them: the next sections use those errors.

2. The header and the column positions

Read the first record on its own, check that the columns you need are there, and remember their positions. Then a reordered export still works, and a wrong file stops at once with a clear message.

main.go
package main

import (
	"encoding/csv"
	"fmt"
	"os"
)

var required = []string{"evaluation_id", "question_id", "score", "comment"}

// columnPositions maps each required column to its position in the header.
func columnPositions(header []string) (map[string]int, error) {
	positions := map[string]int{}
	for i, name := range header {
		positions[name] = i
	}
	for _, name := range required {
		if _, ok := positions[name]; !ok {
			return nil, fmt.Errorf("the header has no %q column; it has %q", name, header)
		}
	}
	return positions, nil
}

func main() {
	file, err := os.Open("responses.csv")
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer file.Close()

	reader := csv.NewReader(file)
	header, err := reader.Read()
	if err != nil {
		fmt.Fprintln(os.Stderr, "reading the header:", err)
		os.Exit(1)
	}
	positions, err := columnPositions(header)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Println(positions)
}
$ go run .
map[comment:3 evaluation_id:0 question_id:1 score:2]

3. The invisible character from Excel

Export the same sheet from Excel as “CSV UTF-8”, and the same program fails:

$ go run .
the header has no "evaluation_id" column; it has ["\ufeffevaluation_id" "question_id" "score" "comment"]
exit status 1

The first column is "\ufeffevaluation_id": Excel starts the file with a byte order mark, the invisible character U+FEFF, and %q is what makes it visible. Remove it from the first header name before you look the columns up: header[0] = strings.TrimPrefix(header[0], "\ufeff"). The build day does exactly that.

Bad rows

4. Shape errors: *csv.ParseError

A row with the wrong number of fields, or a broken quote, comes back with a *csv.ParseError. It carries the line and the problem, and errors.Is(err, csv.ErrFieldCount) tells you which kind it is (the error-wrapping lesson).

The reader stays usable after a ParseError: report the row, count it, and keep reading. Only a real read error (the disk, the network) should stop the loop.

main.go
package main

import (
	"encoding/csv"
	"errors"
	"fmt"
	"io"
	"os"
)

func main() {
	file, err := os.Open("responses.csv")
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer file.Close()

	reader := csv.NewReader(file)
	good, bad := 0, 0
	for {
		_, err := reader.Read()
		if errors.Is(err, io.EOF) {
			break
		}
		var parseErr *csv.ParseError
		if errors.As(err, &parseErr) {
			fmt.Fprintln(os.Stderr, "skipped:", err)
			bad++
			continue
		}
		if err != nil {
			fmt.Fprintln(os.Stderr, "reading responses.csv:", err)
			os.Exit(1)
		}
		good++
	}
	fmt.Printf("%d good records, %d bad\n", good, bad)
}
$ go run .
skipped: record on line 4: wrong number of fields
skipped: parse error on line 8, column 11: extraneous or missing " in quoted-field
6 good records, 2 bad

The reader learns the number of fields from the first record, the header, and checks every row against it. Line 4 has three fields instead of four. Line 8 has "4"x: a quoted field with something after the closing quote, so the reader cannot know where the field ends.

6 good records: the header and five answers. The six on line 5 and the empty comment on line 9 are fine as CSV; whether they are fine as answers is the next section.

5. Content errors, with the line number

A score of six is valid CSV and an invalid answer. Check each value, and report it with the line it came from: reader.FieldPos(i) gives the line and column where field i of the current record started.

main.go
package main

import (
	"encoding/csv"
	"errors"
	"fmt"
	"io"
	"os"
	"strconv"
)

const scoreColumn = 2

func parseScore(text string) (int, error) {
	score, err := strconv.Atoi(text)
	if err != nil || score < 1 || score > 5 {
		return 0, fmt.Errorf("score must be a whole number from 1 to 5, got %q", text)
	}
	return score, nil
}

func main() {
	file, err := os.Open("responses.csv")
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer file.Close()

	reader := csv.NewReader(file)
	if _, err := reader.Read(); err != nil {
		fmt.Fprintln(os.Stderr, "reading the header:", err)
		os.Exit(1)
	}

	total, count := 0, 0
	for {
		record, err := reader.Read()
		if errors.Is(err, io.EOF) {
			break
		}
		var parseErr *csv.ParseError
		if errors.As(err, &parseErr) {
			fmt.Fprintln(os.Stderr, "skipped:", err)
			continue
		}
		if err != nil {
			fmt.Fprintln(os.Stderr, "reading responses.csv:", err)
			os.Exit(1)
		}

		score, err := parseScore(record[scoreColumn])
		if err != nil {
			line, _ := reader.FieldPos(scoreColumn)
			fmt.Fprintf(os.Stderr, "skipped: line %d: %v\n", line, err)
			continue
		}
		total += score
		count++
	}
	fmt.Printf("%d scores, average %.2f\n", count, float64(total)/float64(count))
}
$ go run .
skipped: record on line 4: wrong number of fields
skipped: line 5: score must be a whole number from 1 to 5, got "six"
skipped: parse error on line 8, column 11: extraneous or missing " in quoted-field
4 scores, average 3.75

The column is ignored from FieldPos with _: the line is enough for a person to find the row. Every skipped row says why, on stderr, and the summary says how many were used, so nobody mistakes an average of 4 answers for an average of 7.

A real tool also needs a limit: a file where half the rows are bad is the wrong file, and should stop with an error, not produce an average. The build day adds it.

Writing

6. csv.Writer, Flush and Error

csv.NewWriter quotes fields when they need it. It buffers what you write, so you must call Flush at the end, and then Error to learn whether anything failed.

main.go
package main

import (
	"encoding/csv"
	"fmt"
	"os"
)

func main() {
	writer := csv.NewWriter(os.Stdout)

	rows := [][]string{
		{"evaluation_id", "average", "note"},
		{"9001", "4.50", "Good pace, but the room was cold"},
		{"9003", "2.00", "Said \"too fast\""},
	}
	for _, row := range rows {
		if err := writer.Write(row); err != nil {
			fmt.Fprintln(os.Stderr, "writing a row:", err)
			os.Exit(1)
		}
	}

	writer.Flush()
	if err := writer.Error(); err != nil {
		fmt.Fprintln(os.Stderr, "writing the CSV:", err)
		os.Exit(1)
	}
}
$ go run .
evaluation_id,average,note
9001,4.50,"Good pace, but the room was cold"
9003,2.00,"Said ""too fast"""

The comma and the quotes were escaped the CSV way: the field is quoted, and a quote inside becomes two quotes. Without Flush, a short output may never leave the buffer, and the program prints nothing at all, with no error. It is the CSV version of a missing scanner.Err().

Coming from PHP

ImportResponses.php
<?php
$handle = fopen($path, 'r');
$header = fgetcsv($handle);                       // the BOM stays in $header[0] here too

while (($row = fgetcsv($handle)) !== false) {     // no error for a row with 3 fields:
    $score = (int) $row[2];                        // a short row is just a shorter array,
}                                                 // and (int) 'six' is 0

fgetcsv streams too, and handles quotes the same way. What it does not do is tell you about a row with the wrong number of fields, or give you a line number for it: a short row is a shorter array, and $row[3] is a warning and null. Go’s reader returns an error you can report, and keeps going.

Laravel Excel and League CSV add the checks PHP’s function lacks. In Go they are in the standard reader, and the rest is 20 lines of your own.

PracticeLearn Go with Tests: Maps; a column check

Do Maps in Learn Go with Tests: it adds errors to a map-based dictionary, the same pattern as columnPositions.

Exercise: test columnPositions

Move columnPositions from section 2 into a function that also removes the byte order mark, and write a table test for it: the normal header, a reordered header, a header with a BOM, a header missing score, and an empty header. Each failure case must check that the error message names the missing column.

Remember

  • Read CSV one record at a time, check the header by name, and strip the BOM from its first column.
  • A *csv.ParseError is a bad row to report and skip; any other error stops the loop.
  • Every buffered writer needs Flush and an Error check.

Tomorrow: structured logging with log/slog, so a tool’s messages can be read by people and by machines.