(text csv)

Reference

Overview

CSV, as RFC 4180 has it: read one row at a time or all at once, and written.

(import (text csv))

(parse-csv "name,age\nAda,36\n")    ; (Ok [#iarray["name" "age"] #iarray["Ada" "36"]])
(parse-csv (csv-file "data.tsv") #:separator #\tab)
(csv-fold (csv-file "big.csv") 0 (fun (row n) (+ n 1)))   ; the number of rows
(csv->string [["a" "b,c"] ["d \"e\"" ""]])  ; "a,\"b,c\"\n\"d \"\"e\"\"\",\n"

Three layers for reading, each built on the one below: csv-next!, a pull reader as OCaml’s Csv.next has it; csv-fold and csv-for-each, which hold one row at a time; and parse-csv, the whole document. A row is an (IArray string): one array, and no object of its own, which is the cheapest row there is. The writer takes a row as any Iterable of strings, so a row read is written as it is.

Every reader takes a source, anything with a CsvSource implementation, and the same options.

Records of your own, read by the header’s column names and written back, are (text csv-codec)’s: its def/csv-type declares a record and how it reads from a row.

Options.

keyworddefaultwhat it does
#:separator#\,the character between fields
#:quote-char(Some #\")the quote; None reads every field as it is
#:strict?#t#f accepts quotes in the wrong place

The separator and the quote have to be ASCII characters that do not end a line, and different from each other. Anything else raises an ArgumentException.

What is read. A row ends at LF, CR LF or CR alone, or at the end of the input. A field that starts with the quote ends at the next quote that is not doubled. In it, a doubled quote is one quote, and the separator and line ends are part of the text. A blank line is not a row, and a line end after the last row does not make an empty row. A byte order mark at the start is skipped. Rows can have different numbers of fields.

Strict and not. When strict, which is the default, these are errors: a quote in a field that does not start with one, something other than the separator or a line end after a closing quote, and the end of the input inside quotes. With #:strict? #f, as Python’s csv reads: the quote in the first case is part of the field; in the second, the text up to the next separator is added to the field; in the third, the field ends with the input.

Encodings. The input is UTF-8, and a field with bytes that are not is an error. To read another encoding, put the port through reencode-input-port from (std ports) first.

Errors. What is wrong with the input is a CsvError, in a Result, with its line, row and field. An exception your own function raises passes through as it was. A reader streams, so one that fails at a row has already given every row before it.

Writing. A field is written in quotes only when it holds the separator, the quote, CR or LF, or when it is the only field of its row and empty, as "". So every row reads back as it was written, except a row with no fields, which is written as an empty line.

See also: parse-csv, csv-fold, csv-for-each, call-with-csv-reader, csv->string, write-csv, CsvSource

Reference

Types

Functions

Types

CsvError

record ↑ Types

What is wrong with the input, and where.

message
What is wrong.
line
The line where the error is, from 1. For a quoted field that is not closed, the line where it starts.
row
The row, from 1. Blank lines are not rows.
field
The field in that row, from 1.

displayed writes all of it on one line: line 3, row 2, field 4: a quote inside a field that does not start with one.

CsvInput

union ↑ Types

What a source is read as: what csv-input answers.

Opaque. A type of your own gets one by handing csv-input something that already has a CsvSource implementation.

See also: CsvSource, csv-input

CsvSource

trait ↑ Types

What can be read as CSV.

%s
The source's type.
(impl (CsvSource Upload)
  (defun (csv-input u) (csv-input (upload-port u))))

These have an implementation:

stringthe CSV itself
InputPortread from where the port is, a chunk at a time; left open
(csv-file path)opened through the FS effect and closed again

A port you hand over stays open: whoever opens a resource closes it.

See also: csv-input, csv-file

CsvFile

record ↑ Types

A path to read CSV from, as opposed to a string of CSV.

See also: csv-file

CsvReader

record ↑ Types

An input being read, row by row.

See also: call-with-csv-reader, csv-next!

Functions

csv-input

function ↑ Functions

(: csv-input (-> %s CsvInput))

A source as the reader takes it.

source
The source.
returns
What it reads as.

See also: CsvSource

csv-file

function ↑ Functions

(: csv-file (-> string CsvFile))
(csv-file path)

A file to read, as a source.

path
The file's path.
returns
A source the reader opens, through the FS effect, and closes again.
(parse-csv (csv-file "data.csv"))

Nothing is opened until a reader reads it. A file that cannot be opened then raises, as file-read-text does; it is not a CsvError.

See also: CsvSource

call-with-csv-reader

function ↑ Functions

(: call-with-csv-reader (-> %s (-> CsvReader %a) (#:separator char) (#:quote-char (Option char)) (#:strict? bool) %a))
(call-with-csv-reader source proc #:separator #\, #:quote-char (Some #\") #:strict? #t)

Calls a function with a reader that gives the rows of an input one at a time.

source
What to read.
proc
Called with the reader. A file is closed when it returns.
#:separator
The character between fields.
#:quote-char
The quote, or None for no quoting.
#:strict?
Whether a quote in the wrong place is an error.
returns
What proc answers.
raises ArgumentException
When the separator or the quote is not allowed.
raises System.IO.IOException
When the source is a csv-file that cannot be opened.
;; The first row, and nothing after it is read.
(call-with-csv-reader (csv-file "data.csv") csv-next!)

(call-with-csv-reader port
  (fun (r)
    (match (csv-next! r)
      ((Ok (Some row)) ...)
      ((Ok None) ...)                     ; the end of the input
      ((Err e) ...))))

The bottom layer. The reader is for proc’s use only. It reads from the port only as far as the rows it gives need, a chunk at a time.

See also: csv-next!, csv-fold

csv-next!

function ↑ Functions

(: csv-next! (-> CsvReader (Result CsvError (Option (IArray string)))))
(csv-next! rd)

The next row of an input.

rd
The reader.
returns
Some row, None at the end of the input, or the error. After an error, the same error again.

See also: call-with-csv-reader, csv-row-line, csv-row-number

csv-row-line

function ↑ Functions

(: csv-row-line (-> CsvReader int))
(csv-row-line rd)

The line the row last read starts on.

rd
The reader.
returns
The line, from 1. A quoted field can hold line ends, so a row can go on past it.

For a reader built on csv-next! that finds something wrong with a row that is good CSV, such as a field that is not a number, and wants to say where, as (text csv-codec) does.

See also: csv-row-number, csv-next!

csv-row-number

function ↑ Functions

(: csv-row-number (-> CsvReader int))
(csv-row-number rd)

How many rows have been read, the last one included.

rd
The reader.
returns
The number of the row last read, from 1, or 0 before the first. Blank lines are not rows.

See also: csv-row-line, csv-next!

csv-fold

function ↑ Functions

(: csv-fold (-> %s %seed (-> (IArray string) %seed %seed) (#:separator char) (#:quote-char (Option char)) (#:strict? bool) (Result CsvError %seed)))
(csv-fold source seed f #:separator #\, #:quote-char (Some #\") #:strict? #t)

A seed threaded through the rows of an input.

source
What to read.
seed
The seed to begin with.
f
Called with each row and the seed; answers the next seed.
#:separator
The character between fields.
#:quote-char
The quote, or None for no quoting.
#:strict?
Whether a quote in the wrong place is an error.
returns
The final seed, or the error.
raises ArgumentException
When the separator or the quote is not allowed.
raises System.IO.IOException
When the source is a csv-file that cannot be opened.
;; The sum of the second column, without the header.
(csv-fold (csv-file "sales.csv") (Tuple #t 0)
          (fun (row seed)
            (def (Tuple header? total) seed)
            (if header?
                (Tuple #f total)
                (Tuple #f (+ total (string->int (iarray-ref row 1)))))))

One row is held at a time, so the input can be bigger than memory. The rows before an error have been folded when the error is answered.

See also: csv-for-each, parse-csv

csv-for-each

function ↑ Functions

(: csv-for-each (-> %s (-> (IArray string) void) (#:separator char) (#:quote-char (Option char)) (#:strict? bool) (Result CsvError Unit)))
(csv-for-each source f #:separator #\, #:quote-char (Some #\") #:strict? #t)

Calls a function with each row of an input.

source
What to read.
f
Called with each row, in order.
#:separator
The character between fields.
#:quote-char
The quote, or None for no quoting.
#:strict?
Whether a quote in the wrong place is an error.
returns
Ok at the end of the input, or the error.
raises ArgumentException
When the separator or the quote is not allowed.
raises System.IO.IOException
When the source is a csv-file that cannot be opened.
(csv-for-each (csv-file "data.csv") (fun (row) (println (iarray-ref row 0))))

See also: csv-fold

parse-csv

function ↑ Functions

(: parse-csv (-> %s (#:separator char) (#:quote-char (Option char)) (#:strict? bool) (Result CsvError (Vec (IArray string)))))
(parse-csv source #:separator #\, #:quote-char (Some #\") #:strict? #t)

Reads every row of an input.

source
What to read.
#:separator
The character between fields.
#:quote-char
The quote, or None for no quoting.
#:strict?
Whether a quote in the wrong place is an error.
returns
The rows, or the first error.
raises ArgumentException
When the separator or the quote is not allowed.
raises System.IO.IOException
When the source is a csv-file that cannot be opened.
(parse-csv "a,\"b,c\"\r\n\"say \"\"hi\"\"\",\n")   ; (Ok [#iarray["a" "b,c"] #iarray["say \"hi\"" ""]])
(parse-csv "a,b\"c")                              ; (Err ...): a quote inside a field
(parse-csv "a,b\"c" #:strict? #f)                 ; (Ok [#iarray["a" "b\"c"]])

See also: csv-fold, call-with-csv-reader

csv-row-end

function ↑ Functions

(: csv-row-end (-> (Array byte) int (#:quote-char (Option char)) (Option int)))
(csv-row-end bytes from #:quote-char (Some #\"))

Where the row that starts at an index ends.

bytes
CSV text as UTF-8 bytes.
from
The index of the first byte of a row, not inside quotes.
#:quote-char
The quote, or None for no quoting.
returns
Some of the index just after the line feed that ends the row, or None when no line feed ends it, as for the last row of a text without a final line feed.
raises ArgumentException
When the index is not in the bytes, or the quote is not allowed.
(csv-row-end (string->bytes "a,b\n1,2\n") 0)          ; (Some 4)
(csv-row-end (string->bytes "\"x\ny\",1\n2,3\n") 0)   ; (Some 8): the first line feed is inside quotes
(csv-row-end (string->bytes "a,b") 0)                 ; None

A line feed is inside quotes when the quotes before it, from the start of the row, are odd in number. A quote inside a quoted field is two quotes, so it does not change that. A CR before the line feed is part of the row.

See also: csv-cut-rows

csv-cut-rows

function ↑ Functions

(: csv-cut-rows (-> (Array byte) int (#:from int) (#:quote-char (Option char)) (Option (Array int))))
(csv-cut-rows bytes parts #:from 0 #:quote-char (Some #\"))

CSV bytes cut into pieces of whole rows, for reading on several threads.

bytes
CSV text as UTF-8 bytes.
parts
The largest number of pieces. 1 or more.
#:from
The index of the first byte of a row where the first piece starts, as the end of a header. 0 by default.
#:quote-char
The quote, or None for no quoting.
returns
Some of the index where each piece starts, and then the end of the bytes: k pieces are k + 1 indices. None when the quotes do not close.
raises ArgumentException
When the number of pieces is less than 1, #:from is not in the bytes, or the quote is not allowed.
(def b (string->bytes "h\n1\n2\n3\n4\n"))
(csv-cut-rows b 2 #:from 2)                  ; (Some #[2 6 10]): the rows 1 and 2, and 3 and 4
(csv-cut-rows (string->bytes "\"a\n") 2)     ; None: the quote is not closed

The pieces are of about one size. Each piece is whole rows: a cut is just after a line feed that is not inside quotes, and the last piece ends at the end of the bytes, with or without a final line feed. No piece is empty, so a small text gives fewer pieces than asked for, and bytes with no rows after #:from give no piece: (Some #[n]).

The quotes of each piece are counted with one vectorized call. Then, from the point where each piece would start if all were of one size, the bytes are looked at only up to the next line feed outside quotes.

The bytes are not checked to be UTF-8, nor the rows to be CSV: a reader of the pieces does that. A quote inside a field that does not start with a quote, which strict reading refuses, changes the parity and so the cuts.

See also: csv-row-end

csv-row->string

function ↑ Functions

(: csv-row->string (-> %row (#:separator char) (#:quote-char (Option char)) (#:quote-all? bool) string))
(csv-row->string row #:separator #\, #:quote-char (Some #\") #:quote-all? #f)

One row as CSV text, without a line end.

row
The fields: a vec, an IArray, a list, or any other Iterable of strings.
#:separator
The character between fields.
#:quote-char
The quote, or None for no quoting.
#:quote-all?
When #t, every field is in quotes.
returns
The text.
raises ArgumentException
When the separator or the quote is not allowed, or when a field needs quotes and #:quote-char is None.
(csv-row->string ["a" "b,c" "say \"hi\""])   ; "a,\"b,c\",\"say \"\"hi\"\"\""
(csv-row->string [""])                       ; "\"\"", which reads back as one empty field

See also: csv->string, write-csv-row

csv->string

function ↑ Functions

(: csv->string (-> %rows (#:separator char) (#:quote-char (Option char)) (#:quote-all? bool) (#:crlf? bool) string))
(csv->string rows #:separator #\, #:quote-char (Some #\") #:quote-all? #f #:crlf? #f)

Rows as CSV text, each ended by a line end.

rows
The rows: a vec, a list, a Seq, or anything else that iterates over rows. A row is any Iterable of strings: a vec, an IArray, a list.
#:separator
The character between fields.
#:quote-char
The quote, or None for no quoting.
#:quote-all?
When #t, every field is in quotes.
#:crlf?
When #t, lines end with CR LF, as RFC 4180 says. Else with LF.
returns
The text. parse-csv reads it back as the same rows, with the same options.
raises ArgumentException
When the separator or the quote is not allowed, or when a field needs quotes and #:quote-char is None.

See also: write-csv, parse-csv

write-csv-row

function ↑ Functions

(: write-csv-row (-> OutputPort %row (#:separator char) (#:quote-char (Option char)) (#:quote-all? bool) (#:crlf? bool) void))
(write-csv-row port row #:separator #\, #:quote-char (Some #\") #:quote-all? #f #:crlf? #f)

Writes one row and its line end to a port.

port
The port.
row
The fields: a vec, an IArray, a list, or any other Iterable of strings.
#:separator
The character between fields.
#:quote-char
The quote, or None for no quoting.
#:quote-all?
When #t, every field is in quotes.
#:crlf?
When #t, the line ends with CR LF. Else with LF.
raises ArgumentException
When the separator or the quote is not allowed, or when a field needs quotes and #:quote-char is None.

For output made a row at a time. The row is made first, and written in one piece.

See also: write-csv, csv-row->string

write-csv

function ↑ Functions

(: write-csv (-> OutputPort %rows (#:separator char) (#:quote-char (Option char)) (#:quote-all? bool) (#:crlf? bool) void))
(write-csv port rows #:separator #\, #:quote-char (Some #\") #:quote-all? #f #:crlf? #f)

Writes rows to a port, each ended by a line end.

port
The port.
rows
The rows: a vec, a list, a Seq, or anything else that iterates over rows. A row is any Iterable of strings: a vec, an IArray, a list.
#:separator
The character between fields.
#:quote-char
The quote, or None for no quoting.
#:quote-all?
When #t, every field is in quotes.
#:crlf?
When #t, lines end with CR LF, as RFC 4180 says. Else with LF.
raises ArgumentException
When the separator or the quote is not allowed, or when a field needs quotes and #:quote-char is None.

The rows are read once, in order. The text goes to the port in pieces of about 64 KiB, so a Seq of rows is written while it is made, and the whole document is never in memory.

See also: csv->string, write-csv-row