csv — CSV tables
mzs
include csvINFO
Available in bot scripts. There are no files there: CSV comes as a string, for example in a bot.http response.
| Function | What it does |
|---|---|
csv.parse(s, opts) | text → an array of records (arrays or dicts) |
csv.rows(src, opts) | the same, lazily, one record at a time; src is a seq of lines, an array or a string |
csv.str(rows, opts) | records → text, each line with "\n" |
csv.line(row, opts) | one record → a line without "\n" |
| Option | Default | What it does |
|---|---|---|
sep | "," | separator: ";", "\t" |
header | false | the first line holds field names; or an array of names |
strict | true | all records have the same number of fields |
trim | false | strip spaces around unquoted fields |
comment | nil | skip lines starting with this character |
s.split(",") is not CSV parsing: it breaks on quotes and on commas inside fields.
Reading
mzs
include csv
csv.parse("id,name\n1,Ann\n") # → [["id","name"],["1","Ann"]]
csv.parse("id,name\n1,Ann\n", {header: true}) # → [{"id":"1","name":"Ann"}]
csv.parse("1,Ann\n2,Bo", {header: ["id", "name"]}) # → [{"id":"1","name":"Ann"},{"id":"2","name":"Bo"}]
csv.parse('a;"b;c";"say ""hi"""', {sep: ";"}) # → [["a","b;c","say \"hi\""]]All values are strings; convert numbers yourself:
mzs
include csv
orders = csv.parse("qty,price\n2,1500\n1,3200", {header: true})
orders.sum { it["qty"].int * it["price"].int } # → 6200Ragged lines and comments:
mzs
include csv
csv.parse("a,b\n1", {strict: false}) # → [["a","b"],["1",null]]
csv.parse("# export\na,b", {comment: "#"}) # → [["a","b"]]
csv.parse(" a , b ", {trim: true}) # → [["a","b"]]Reading one record at a time
csv.rows does not hold the whole file in memory.
mzs
include csv
csv.rows("name,paid\nAnn,yes\nBo,no\nCy,yes", {header: true}).filter { it["paid"] == "yes" }.count # → 2In the terminal, line by line from stdin:
mzs
include io
include csv
paid = csv.rows(io.lines, {header: true}).filter { it["paid"] == "yes" }.countsh
mzs paid.mzs < orders.csvWriting
For dicts, the header comes from the first record's keys. Quotes go only where needed.
mzs
include csv
print(csv.str([{id: 1, who: "Petrov, Ivan"}, {id: 2, who: "Ann"}]))
print(csv.str([[1, 2], [3, 4]], {sep: ";"}))text
id,who
1,"Petrov, Ivan"
2,Ann
1;2
3;4mzs
include csv
println(csv.line(["a", "b,c", nil, 3]))text
a,"b,c",,3nil is an empty field. A key missing from header is an error: data is not lost silently.
Errors
Broken input is a csv error with the line and column number in e["data"].
mzs
include csv
try csv.parse("a,b\n\"unclosed") else (e) -> [e["kind"], e["data"]] # → ["csv",{"line":2,"col":1}]
try csv.parse("a,b\n1") else (e) -> e["kind"] # → "csv"
try csv.parse("a;b", {sepp: ";"}) else (e) -> e["kind"] # → "argument"