Skip to content

@csv

Import this module with import @csv.

Reading and writing CSV (Comma-Separated Values) data.

Function Signature Description
parse (csv_string string) -> [[string]] Parse CSV string to 2D array
parse_delimited (csv_string string, delimiter char) -> [[string]] Like parse, but fields split on delimiter (e.g. '\t', ';'); RFC 4180 quoting still applies
detect_delimiter (sample string) -> char Most frequent of , ; \t | on the first line of sample, defaulting to ,
encode (data [[string]]) -> string Encode 2D array to CSV string; a field containing ,, ", CR, or LF is quoted per RFC 4180 with embedded " doubled
read_file (path string) -> ([[string]], Error) Read and parse CSV file — always use destructuring
write_file (path string, data [[string]]) -> (bool, Error) Write 2D array to CSV file (same RFC 4180 quoting as encode) — always use destructuring
headers (data [[string]]) -> [string] Extract header row from parsed CSV data
to_maps (data [[string]]) -> [map[string:string]] Rows 1..N as maps keyed by header name (short row omits keys, long row drops extras); <= 1 row gives an empty array
from_maps (rows [map[string:string]]) -> [[string]] Inverse of to_maps; header is the union of keys in first-seen order, a missing key becomes ""
column (data [[string]], name string) -> [string] Values under header name, excluding the header cell; panics (P0125) if name is not a header
select (data [[string]], names [string]) -> [[string]] Project the named columns in order, keeping the header row; panics (P0125) on an unknown name
filter_rows (data [[string]], predicate func([string]) -> bool) -> [[string]] Keep row 0 unconditionally and each later row where predicate is true; the header is never passed to predicate
sort_by_column (data [[string]], name string) -> [[string]] New array with data rows stably sorted ascending lexicographically by column name; header stays first; panics (P0125) on an unknown name
to_json (data [[string]]) -> string Compact JSON array of objects (via to_maps); every value is a JSON string
to_markdown (data [[string]]) -> string GitHub-flavored Markdown table; row 0 is the header plus a --- separator, | in a cell is escaped, trailing newline