Skip to content

csv

Reading and writing CSV text (RFC 4180) as rows of string fields.

csv.parse turns text into Vec<Vec<Str>>: one inner Vec per row, one Str per field. Every field stays a string; convert with to_i64, to_f64 and so on. The first row is not treated specially, so if the file has a header, use row 0 to find column positions.

Parse a file with a header row:

import csv
let text = "name,age\nann,31\n\"Smith, Bob\",27\n"
let rows = try csv.parse(&text)
let mut age_col = 0
for i in 0..rows[0].len() {
if rows[0][i] == "age" {
age_col = i
}
}
for i in 1..rows.len() {
let age = rows[i][age_col].to_i64().unwrap_or(0)
print(f"{rows[i][0]} is {age}")
}
ann is 31
Smith, Bob is 27

Write rows back to text. Fields are quoted only when they need it (they contain the separator, a quote, a line break, or start or end with a space). Lines end with \n; text_with(&rows, ',', &"\r\n") writes the \r\n that RFC 4180 and Excel expect, or uses another separator:

import csv
let rows = [["id", "note"], ["1", "says \"hi\""], ["2", "a, b"]]
let out = csv.text(&rows)
print(out.replace("\n", "|"))
id,note|1,"says ""hi"""|2,"a, b"|

Other separators, such as ; or tab, go through parse_with. The separator is a byte, written as a character literal:

import csv
let rows = try csv.parse_with(&"a;b;c\n1;2;3\n", ';')
print(rows[1][2])
3
import csv
pub fn parse_with(text: &Str, sep: i64) -> Vec<Vec<Str>> ! CsvError

RFC 4180: fields split by sep, a field in quotes may hold sep, quotes (doubled) and line breaks.

Accepts \n and \r\n line ends. A quoted field may contain the separator, doubled quotes ("" for one ") and line breaks. A missing final line break is fine.

Blank lines are skipped. A line holding only "" is a row with one empty field.

import csv
let rows = try csv.parse(&"a,b\n\n1,2\n\"\"\n")
print(rows.len())
print(rows[2].len())
3
1

Rows are not required to have the same number of fields. Check row.len() before indexing if the input is not trusted.

pub fn parse(text: &Str) -> Vec<Vec<Str>> ! CsvError
pub fn text(rows: &Vec<Vec<Str>>) -> Str

Rows back to CSV text with , and \n, quoting only the fields that need it.

Always separates with ,; there is no writer for other separators.

pub fn text_with(rows: &Vec<Vec<Str>>, sep: i64, line_end: &Str) -> Str

Like text, with another separator and line end ("\r\n" as RFC 4180 and Excel expect).

pub struct CsvError {
pub message: Str
pub line: i64
}

line is the 1-based line where the problem was found. Errors are a quote in the middle of an unquoted field, text after a closing quote, and a quoted field that never closes.

import csv
let rows = csv.parse(&"a,b\nc,d\"e\n") catch {
csv.CsvError(e) => {
print(f"line {e.line}: {e.message}")
[]
}
}
print(rows.len())
line 2: a quote in the middle of a field
0