Tern

csv

The csv module reads and writes comma-separated values as RFC 4180 describes them, with the same rules as Go's encoding/csv. A field in double quotes may hold commas, line breaks and "" (one quote); \r\n line ends read as \n; empty lines are skipped. Every field is a str: convert numbers with to_int / to_float when you read them and str(n) when you write them.

import csv

fn main():
    text = "name,city,note\nAda,London,\"wrote \"\"the\"\" first program\"\nAlan,\"Wilmslow, Cheshire\",\n"
    match csv.parse(text):
        Ok(rows):
            for row in rows:
                print(len(row), row)
        Err(e):
            print(e)
    print(csv.format([["id", "label"], ["1", "a, b"], ["2", "say \"hi\""]]))
Output
3 ["name", "city", "note"]
3 ["Ada", "London", "wrote "the" first program"]
3 ["Alan", "Wilmslow, Cheshire", ""]
id,label
1,"a, b"
2,"say ""hi"""

Functions

fn parse(text: str) Result[[[str]], str]           every record, as its fields
fn records(text: str) Result[[{str: str}], str]    the first row names the columns; each later row
                                                    is {column: field}
fn reader(text: str) Reader                         one record at a time: r.next(&row) bool, r.err
fn format(rows: [[str]]) str                        rows as CSV text, quoting where needed
fn format_row(row: [str]) str                       one record and its line end
fn options() Options                                the defaults, to change
fn tsv() Options                                    tab-separated values
fn parse_with(text, o)  records_with(text, o)  reader_with(text, o)
fn format_with(rows, o)  format_row_with(row, o)

Records by column name

records uses the first row as the header, which is what most exported spreadsheets have:

import csv

fn main():
    text = "sku,qty,price\nA-1,3,2.50\nB-7,10,0.99\n"
    rows = csv.records(text)
    if rows is Ok(items):
        total = 0.0
        for it in items:
            total += float(it["qty"].to_int(0)) * it["price"].to_float(0.0)
        print(len(items), "items, total", total)
Output
2 items, total 17.4

Big files, one record at a time

parse builds every row. To go through a big file without that, use a reader: r.next(&row) puts the next record in row and returns false at the end, or at an error, which r.err then names (it's "" after a clean end). r.line is the line the next record starts on.

import csv

fn main():
    r = csv.reader("day,visits\nmon,120\ntue,98\nwed\n")
    row: [str] = []
    sum = 0
    while r.next(&row):
        if row[0] != "day":
            sum += row[1].to_int(0)
    print(sum)
    print(r.err)
Output
218
csv: line 4: 1 field, but the first record has 2 fields

Options

csv.options() returns the defaults; change the fields you need and pass them to a _with function:

FieldDefaultDoes
sep","the field separator, one byte (csv.tsv() sets "\t")
comment""lines starting with this byte are skipped
fields0fields per record: 0 as many as the first record, n exactly n, -1 any number
lazy_quotesfalsea " inside an unquoted field, or a lone " in a quoted one, is kept as text
trim_leading_spacefalsespaces, tabs, \r, \v and \f before each field are dropped
crlffalseformat ends lines with \r\n
import csv

fn main():
    o = csv.options()
    o.sep = ";"
    o.comment = "#"
    o.fields = -1
    print(csv.parse_with("# export of 2026-10-01\na;b;c\n1;2\n", o))
    print(csv.parse_with("x\ty\n", csv.tsv()))
Output
Ok([["a", "b", "c"], ["1", "2"]])
Ok([["x", "y"]])

Errors

Malformed input is an Err naming the line and column (1-based, in bytes), never a partial result:

import csv

fn main():
    print(csv.parse("a,b\"c\n"))
    print(csv.parse("a,\"b\"c\n"))
    print(csv.parse("a,\"never closed\n"))
    print(csv.parse("a,b\n1,2,3\n"))
Output
Err("csv: line 1, column 4: bare " in a field without quotes (quote the field and double the ")")
Err("csv: line 1, column 6: text after the closing quote of a field ("" is a quote inside one)")
Err("csv: line 1, column 3: a quoted field is never closed")
Err("csv: line 2: 3 fields, but the first record has 2 fields")

Writing

format quotes a field only when it must: when it holds the separator, a quote, \r or \n, or starts with a space or tab. Quotes inside are doubled. A record that is one empty field is written as "", so it reads back as a record and not as a skipped empty line. What format writes, parse reads back to the same rows.

Speed

bench/std compares it with Go's encoding/csv and Rust's csv crate on 40 MB of 8-field rows, with and without quoted fields: Tern is the fastest of the three at writing, at reading one record at a time (1.1-1.4x Rust, 2-2.6x Go) and at parse (3.4-4.4x Rust, which allocates every field, and about 2x Go). A reader allocates nothing per record once its row's strings are big enough. The numbers are in bench/std/results.md.

Source: docs/std/csv.md. Every example on this page is compiled and run by tern x test docs.