Csv
import "std/data" (included in import "std") · namespace std.data
Reading and writing CSV (comma-separated values), the plain-text table format that spreadsheets import and export. It follows RFC 4180: fields containing the separator, quotes or line breaks are wrapped in quotes, and a quote inside a field is written twice.
grav
import "std"
fn main() {
let text = "name,city,note\nAda,London,\"likes \"\"math\"\"\"\nGrace,\"New York, NY\",\n"
let rows = Csv.parse(text)
print(rows.size())
print(rows[2][1])
for (person in Csv.parseRecords(text)) {
print("${person["name"]} lives in ${person["city"]}")
}
let out: Array<Array<string>> = [["id", "label"], ["1", "plain"], ["2", "has, comma"]]
print(Csv.format(out))
print(Csv.parseWith("a;b\n1;2", ";"))
}3
New York, NY
Ada lives in London
Grace lives in New York, NY
id,label
1,plain
2,"has, comma"
[["a", "b"], ["1", "2"]]parsereturns every row as anArray<string>;parseRecordsuses the first row as column names and returns oneHashMapper following row.- Lines may end in
\nor\r\n; a final blank line is ignored. - The
...Withvariants take another one-character separator, such as"\t"or";". - A quoted field that is never closed throws
ValueError. - To read a large CSV file line by line, remember that a quoted field may span lines; parsing whole files with
parseis simplest.
API
class Csv
Parsing and formatting CSV text.
Static members
static fn parse(text: string) -> Array<Array<string>>— The rows of comma-separatedtext, each a list of fields. A blank last line is ignored. ValueError for a quote that is never closed.static fn parseWith(text: string, sep: string) -> Array<Array<string>>— The rows oftextwith fields separated bysep(one character, such as "\t" or ";").static fn parseRecords(text: string) -> Array<HashMap<string, string>>— The rows after the first, each as a map from the first row's column names to the row's values (missing fields are "").static fn parseRecordsWith(text: string, sep: string) -> Array<HashMap<string, string>>— The same as parseRecords, with fields separated bysep.static fn quote(field: string) -> string— One field, quoted when it contains the separator, a quote or a line break.static fn quoteWith(field: string, sep: string) -> string— One field, quoted when it containssep, a quote or a line break.static fn formatRow(row: Array<string>) -> string— One row as a CSV line (without the line break).static fn formatRowWith(row: Array<string>, sep: string) -> string— One row with fields separated bysep.static fn format(rows: Array<Array<string>>) -> string— Rows as CSV text, each line ending in "\n".static fn formatWith(rows: Array<Array<string>>, sep: string) -> string— Rows as text with fields separated bysep.