Skip to content

CSV

mash.csv · Files & Storage

mash.csv reads a CSV file from a share and builds new CSV text. Use it for exports, logs and any spreadsheet someone saved as CSV. For an .xlsx workbook, use mash.xlsx or mash.sheet.

Reading and writing are separate. read(file) opens a File and gives you a reader. writer() gives you an empty writer that builds text in memory. Nothing reaches a share until you write that text with the folder’s write.

A reader needs a header decision. By default the first row is data. Call setHeaderOffset(0) and each record becomes a dictionary keyed by the header names, and getHeader() lists the names. Use getRecords() to go through the rows.

A writer quotes for you. insertOne takes one row (a list), insertAll takes many. Commas, quotes and line breaks inside a value are escaped, so Widget, large stays one cell. toString() gives the CSV text.

Text is UTF-8 unless you add a byte-order mark. mash.csv.bom_utf8 holds the marker some versions of Excel look for.

Build CSV text:

set w to mash.csv.writer()
w.insertOne(["name", "qty"])
w.insertAll([["Widget, large", 4], ["Bolt", 12]])
printline w.toString()
name,qty
"Widget, large",4
Bolt,12

Save it to a share:

set w to mash.csv.writer()
w.insertOne(["name", "qty"])
w.insertOne(["Bolt", 12])
set folder to mash.files.get("Finance", "Reports")
folder.write("stock.csv", w.toString())

Read a CSV with a header row and add up a column:

set csv to mash.files.get("Finance", "Reports/stock.csv")
set reader to mash.csv.read(csv)
reader.setHeaderOffset(0)
set total to 0
each reader.getRecords() as row
increment total by row["qty"]
end
printline "Total: {{total}}"

Check the columns are what you expect before you trust the file:

set reader to mash.csv.read(mash.files.get("Finance", "Reports/stock.csv"))
reader.setHeaderOffset(0)
if mash.collect(reader.getHeader()).join("|") is not "name|qty"
fail("stock.csv doesn't have the columns name and qty")
end
  • Cell values are text. row["qty"] is "12". Arithmetic works on numeric text, but tidy a value with mash.str(...).trim() first if the file might hold stray spaces.
  • Adding a row is read, change, write. Two scripts that do this at once can lose a row. Have one script do the writing.
  • Excel doesn’t always guess UTF-8. If accents come out wrong when someone opens your CSV in Excel, start the writer with the marker: mash.csv.writer(mash.csv.bom_utf8).

Files and folders for writing the result, and Collections for sorting and summing rows.

Read and write to CSV files

NameTypeDescription
bom_utf16_be
bom_utf16_le
bom_utf32_be
bom_utf32_le
bom_utf8
types
csv.read(file: File) → Reader

Read a CSV file.

csv.statement() → Statement

Create a CSV query statement for filtering and slicing.

csv.writer(csv?: string = "") → Writer

Create a CSV writer.