[Go] Read a tab-separated file with encoding/csv

Created on November 30, 2026

Set Reader.Comma to '\t' to read tab-separated values (TSV) with Go's encoding/csv package.

Create a TSV file named cities.tsv with a header on the first line. The command inserts a tab between the columns.

printf 'name\tcity\nAlice\tTokyo\nBob\tOsaka\n' > cities.tsv

Save the following program as main.go in the same directory.

package main

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

func readCities(path string) ([][]string, error) {
    file, err := os.Open(path)
    if err != nil {
        return nil, err
    }
    defer file.Close()

    reader := csv.NewReader(file)
    reader.Comma = '\t'
    reader.FieldsPerRecord = 2
    return reader.ReadAll()
}

func main() {
    records, err := readCities("cities.tsv")
    if err != nil {
        log.Fatal(err)
    }

    if len(records) == 0 {
        return
    }

    for _, record := range records[1:] {
        fmt.Printf("%s: %s\n", record[0], record[1])
    }
}

Run the following command from the directory containing both files.

go run main.go

This produces the following output.

Alice: Tokyo
Bob: Osaka

readCities() opens cities.tsv with os.Open() and passes the file to csv.NewReader(). defer file.Close() closes the file when readCities() returns.

The exported field Comma defaults to a comma. Set it to a tab before reading.

The exported field FieldsPerRecord specifies how many fields each record must contain when set to a positive integer. This example sets it to 2, so reading a record with a different number of fields returns an error.

The program returns early when there are no records. Otherwise, records[1:] skips the header.

The reader interprets quoted fields using the rules of encoding/csv.

To process one record at a time without keeping the entire input in memory, use Read() in place of ReadAll().

References

Go