Programming Search⌘K

Formatcore

CSV

Also called Comma-Separated Values.

CSV is a text format for a table. Each line is a record, commas separate the fields, and double quotes enclose a field that holds a comma, a quote or a line break.

What it is

CSV (comma-separated values) is a text format for a table. Each line of the text is a record. Commas separate the fields of a record. The first line can be a header that gives a name to each column.1 The Python documentation calls CSV the most common import and export format for spreadsheets and databases.6

A CSV file has no types. Each field is a string of characters. The text 007 can be a number, a code with leading zeros or a name. The format does not say which. A CSV file also has no schema. It does not say which columns must be there, which fields can be empty, or what the encoding of the text is. The reader must know these facts from somewhere else, or guess them.

CSV is also not one format. There are many dialects. They differ in the delimiter, the quote character, the way to escape a quote and the line end.5 RFC 4180 describes the dialect that most programs share, and this page uses it as the reference.1 Each pitfall on this page comes from a difference between a dialect and RFC 4180, or from a fact that the format does not record.

History

CSV was in use for many years before anyone described it in a standard way.6 RFC 4180 says that the format "has never been formally documented", and that no MIME type for it was registered with IANA. At that time, different programs and operating systems used different MIME types for CSV.1

PEP 305 added the module csv to Python 2.3. The PEP says that the format is "not formally defined by a stable specification". It also says that it is "subtle enough" that a split on commas is "eventually bound to fail".5 The module defined the dialect excel, for the CSV that Excel 97 and Excel 2000 export.5

Yakov Shafranovich wrote RFC 4180 in October 2005. It is an Informational RFC. It "does not specify an Internet standard of any kind". It documents the format "that seems to be followed by most implementations", and it registers the media type text/csv.1 RFC 7111 updated the registration in January 2014.3 The W3C CSV on the Web Working Group published a model for tabular data in December 2015. The model says that "there is no standard for CSV".4

Syntax or structure

RFC 4180 gives seven rules and a grammar in ABNF. The grammar below is a copy of the one in Section 2.1

file = [header CRLF] record *(CRLF record) [CRLF]
header = name *(COMMA name)
record = field *(COMMA field)
name = field
field = (escaped / non-escaped)
escaped = DQUOTE *(TEXTDATA / COMMA / CR / LF / 2DQUOTE) DQUOTE
non-escaped = *TEXTDATA
COMMA = %x2C
CR = %x0D
DQUOTE = %x22
LF = %x0A
CRLF = CR LF
TEXTDATA = %x20-21 / %x23-2B / %x2D-7E

These are the seven rules of Section 2, in short form:1

  1. Each record is on its own line, and a line break (CRLF) ends it.
  2. The last record can end with a line break or without one.
  3. The first line can be a header with the names of the fields. It has the same form as a record and should have the same number of fields.
  4. Commas separate the fields. Each line should have the same number of fields. Spaces are part of a field and should not be ignored. The last field must not have a comma after it.
  5. A field can be in double quotes. A field that is not in double quotes cannot hold a double quote.
  6. A field that holds a line break, a double quote or a comma should be in double quotes.
  7. A double quote inside a quoted field is written as two double quotes.

The rows below show the rules. The field note of the second record holds a comma, two quotes and a line break.

id,name,note
7,"Smith, Ann","said ""hi""
and left"
8,Bo,

The record of id 7 takes two lines of text. A program that reads the file line by line sees four lines, but the file has three records. The record of id 8 has an empty last field. Its line ends with a comma, but this comma separates the second field from the third. It is not a comma after the last field.

The rule TEXTDATA allows only the printable ASCII characters. The CSVW model says that this limit "is routinely ignored in practice".4 Most CSV files hold other characters in UTF-8 or in a legacy encoding.

Section 3 registers the media type text/csv. It has two optional parameters. The parameter charset names the encoding of the text. The parameter header has the value present or absent, and it says if the first line is a header.1 The registration says that text/csv uses CRLF for line breaks, as Section 4.1.1 of RFC 2046 says. It also warns that "some implementations may use other values".2 The registration repeats the robustness principle of RFC 793: "be conservative in what you do, be liberal in what you accept from others".2 The file extension is .csv.1

The grammar has a consequence for blank lines. A record can be one empty field, because non-escaped can be empty. So the grammar reads a blank line as a record with one empty field. A file that ends with two line breaks has an extra record of this kind. The Go reader skips blank lines instead.7

Examples

Python has the module csv in its standard library. The reader below gets three records from the four lines of the text. The line break inside the quoted field stays in the field.6

import csv
import io

text = 'id,name,note\r\n7,"Smith, Ann","said ""hi""\r\nand left"\r\n8,Bo,\r\n'

rows = list(csv.reader(io.StringIO(text, newline="")))
print(len(rows))
for row in rows:
    print(row)

print(len(text.splitlines()))
Output
3
['id', 'name', 'note']
['7', 'Smith, Ann', 'said "hi"\r\nand left']
['8', 'Bo', '']
4

The writer quotes a field only when it holds the delimiter, the quote character or a line break. This is the mode QUOTE_MINIMAL. The writer ends each record with \r\n by default, as RFC 4180 does.6 The integer 7 becomes the text 7, because CSV has no types.

import csv
import io

out = io.StringIO(newline="")
writer = csv.writer(out)
writer.writerow(["id", "name", "note"])
writer.writerow([7, "Smith, Ann", 'said "hi"\nand left'])
writer.writerow([8, "Bo", ""])
print(repr(out.getvalue()))
Output
'id,name,note\r\n7,"Smith, Ann","said ""hi""\nand left"\r\n8,Bo,\r\n'

A split on commas is the usual first attempt at a CSV reader. It breaks the quoted field "Smith, Ann" into two fields and keeps the quotes. PEP 305 gives this case as the reason for the module.5

This code runs but gives a wrong answer on purpose.

line = '7,"Smith, Ann",paid'
print(line.split(","))
Output
['7', '"Smith', ' Ann"', 'paid']

A file must be opened with newline="". The Python documentation says that line breaks inside quoted fields are not read correctly without it.6 In the run below, the \r\n inside the field becomes \n.

import csv
from pathlib import Path

path = Path("notes.csv")
path.write_bytes(b'id,note\r\n7,"line one\r\nline two"\r\n')

with open(path, encoding="utf-8", newline="") as file:
    print(list(csv.reader(file)))

with open(path, encoding="utf-8") as file:
    print(list(csv.reader(file)))
Output
[['id', 'note'], ['7', 'line one\r\nline two']]
[['id', 'note'], ['7', 'line one\nline two']]

The example files show the CSV reader and writer of each language. They also show the behaviour on a byte order mark, on a bad quote and on a row with the wrong number of fields.

PythonGitHub
import csv

data = b"\xef\xbb\xbfzip,city,amount\r\n02134,Boston,12.50\r\n10001,New York\r\n"
with open("people.csv", "wb") as f:
    f.write(data)

with open("people.csv", encoding="utf-8", newline="") as f:
    print(csv.DictReader(f).fieldnames)

with open("people.csv", encoding="utf-8-sig", newline="") as f:
    for row in csv.DictReader(f):
        print(row)
Output
['\ufeffzip', 'city', 'amount']
{'zip': '02134', 'city': 'Boston', 'amount': '12.50'}
{'zip': '10001', 'city': 'New York', 'amount': None}
import csv
import io

for text in ['7,"Smith, Ann"x\r\n', '7,Sm"ith\r\n']:
    print(next(csv.reader(io.StringIO(text, newline=""))))
    try:
        print(next(csv.reader(io.StringIO(text, newline=""), strict=True)))
    except csv.Error as error:
        print("strict:", error)
Output
['7', 'Smith, Annx']
strict: ',' expected after '"'
['7', 'Sm"ith']
['7', 'Sm"ith']
import csv
import io

text = "name;price\r\nTea;3,50\r\n"
dialect = csv.Sniffer().sniff(text)
print(repr(dialect.delimiter))
print(list(csv.reader(io.StringIO(text, newline=""), dialect)))

out = io.StringIO(newline="")
csv.writer(out, delimiter=";").writerow(["Tea", "3,50", "a;b"])
print(repr(out.getvalue()))
Output
';'
[['name', 'price'], ['Tea', '3,50']]
'Tea;3,50;"a;b"\r\n'
import csv
import io

TRIGGERS = ("=", "+", "-", "@", "\t", "\r", "\n")


def safe(cell):
    text = str(cell)
    return "'" + text if text.startswith(TRIGGERS) else text


rows = [["name", "comment"], ["Ann", "=HYPERLINK(\"http://example.com\")"], ["Bo", "-5 points"]]
out = io.StringIO(newline="")
writer = csv.writer(out, quoting=csv.QUOTE_ALL)
for row in rows:
    writer.writerow([safe(cell) for cell in row])
print(out.getvalue(), end="")
Output
"name","comment"
"Ann","'=HYPERLINK(""http://example.com"")"
"Bo","'-5 points"
  • Verdict: stdlib. The csv module has reader and writer for lists, and DictReader and DictWriter for rows keyed by the header.
  • Open files with newline="". The reader then sees each line break inside a quoted field as it is.
  • DictReader gives None for a missing field. It does not raise an error for a short row.
  • The reader is lenient by default. strict=True rejects text after a closing quote, but it still accepts a bare quote inside an unquoted field.
  • The safe function follows the OWASP advice. It adds a single quote before a cell that starts with a formula character, and QUOTE_ALL puts every cell in quotes.
JavaGitHub
import java.io.StringReader;
import java.io.StringWriter;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

public class Main {
    public static void main(String[] args) throws Exception {
        String text = "id,name,note\r\n7,\"Smith, Ann\",\"said \"\"hi\"\"\r\nand left\"\r\n8,Bo,\r\n";
        CSVFormat format = CSVFormat.RFC4180.builder().setHeader().setSkipHeaderRecord(true).get();
        try (CSVParser parser = CSVParser.parse(new StringReader(text), format)) {
            for (CSVRecord record : parser) {
                String note = record.get("note").replace("\r\n", "\\r\\n");
                System.out.println(record.get("id") + " | " + record.get("name") + " | " + note);
            }
        }

        StringWriter out = new StringWriter();
        try (CSVPrinter printer = new CSVPrinter(out, CSVFormat.RFC4180)) {
            printer.printRecord("7", "Smith, Ann", "said \"hi\"");
            printer.printRecord("8", " Bo", "");
        }
        System.out.print(out.toString().replace("\r\n", "\\r\\n\n"));
    }
}
Output
7 | Smith, Ann | said "hi"\r\nand left
8 | Bo |
7,"Smith, Ann","said ""hi"""\r\n
8," Bo",\r\n
import java.io.StringReader;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

public class Main {
    public static void main(String[] args) throws Exception {
        CSVFormat excelFr = CSVFormat.EXCEL.builder().setDelimiter(';').get();
        try (CSVParser parser = CSVParser.parse(new StringReader("name;price\r\nTea;3,50\r\n"), excelFr)) {
            for (CSVRecord record : parser) {
                System.out.println(record.toList());
            }
        }

        try (CSVParser parser = CSVParser.parse(new StringReader("a,b\r\n1,2,3\r\n"), CSVFormat.RFC4180)) {
            for (CSVRecord record : parser) {
                System.out.println(record.size() + " " + record.toList());
            }
        }

        try (CSVParser parser = CSVParser.parse(new StringReader("7,\"Smith\" Ann\r\n"), CSVFormat.RFC4180)) {
            for (CSVRecord record : parser) {
                System.out.println(record.toList());
            }
        } catch (Exception e) {
            System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
        }
    }
}
Output
[name, price]
[Tea, 3,50]
2 [a, b]
3 [1, 2, 3]
UncheckedIOException: org.apache.commons.csv.CSVException: Invalid character between encapsulated token and delimiter at line: 1, position: 11
  • Verdict: library. Java SE has no CSV API. The examples use Apache Commons CSV 1.14.1.
  • CSVFormat holds the dialect. RFC4180, EXCEL, MYSQL, POSTGRESQL_CSV and TDF are predefined, and the builder changes them.
  • The Commons CSV documentation says that the delimiter of Excel depends on the locale. The second example reads a file from a French system with ;.
  • The parser does not check the field count. The ragged row comes back with 3 fields and no error.
using Microsoft.VisualBasic.FileIO;

string text = "id,name,note\r\n7,\"Smith, Ann\",\"said \"\"hi\"\"\r\nand left\"\r\n8,  Bo  ,\r\n";
using (var parser = new TextFieldParser(new StringReader(text)))
{
    parser.SetDelimiters(",");
    parser.HasFieldsEnclosedInQuotes = true;
    while (!parser.EndOfData)
    {
        string[] fields = parser.ReadFields()!;
        Console.WriteLine(string.Join(" | ", fields.Select(f => "[" + f.Replace("\r\n", "\\r\\n") + "]")));
    }
}

using (var parser = new TextFieldParser(new StringReader("8,  Bo  ,\r\n")))
{
    parser.SetDelimiters(",");
    parser.TrimWhiteSpace = false;
    Console.WriteLine(string.Join(" | ", parser.ReadFields()!.Select(f => "[" + f + "]")));
}

using (var parser = new TextFieldParser(new StringReader("1,ok\r\n7,\"Smith\" Ann\r\n9,end\r\n")))
{
    parser.SetDelimiters(",");
    while (!parser.EndOfData)
    {
        try
        {
            Console.WriteLine(string.Join(" | ", parser.ReadFields()!));
        }
        catch (MalformedLineException e)
        {
            Console.WriteLine($"line {e.LineNumber}: {parser.ErrorLine}");
        }
    }
}
Output
[id] | [name] | [note]
[7] | [Smith, Ann] | [said "hi"\r\nand left]
[8] | [Bo] | []
[8] | [  Bo  ] | []
1 | ok
line 2: 7,"Smith" Ann
9 | end
using System.Text;

static string Field(string value) =>
    value.IndexOfAny(['"', ',', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"") + "\"" : value;

string[][] rows = [["id", "name", "note"], ["7", "Smith, Ann", "said \"hi\""], ["8", "Bo", ""]];
var csv = new StringBuilder();
foreach (string[] row in rows)
{
    csv.Append(string.Join(",", row.Select(Field))).Append("\r\n");
}
Console.Write(csv.ToString().Replace("\r\n", "\\r\\n\n"));
Output
id,name,note\r\n
7,"Smith, Ann","said ""hi"""\r\n
8,Bo,\r\n
  • Verdict: stdlib. TextFieldParser in Microsoft.VisualBasic.FileIO ships with .NET and reads delimited and fixed-width text. It has no writer, so the second example writes CSV with a short function.
  • TrimWhiteSpace is true by default, so the parser removes the spaces around Bo. RFC 4180 says that spaces are part of the field.
  • A bad line raises MalformedLineException. ErrorLine holds the text of the line, and the parser goes on with the next line.
JavaScriptGitHub
// Parse RFC 4180 text into rows. Accepts CRLF or LF row ends.
function parseCsv(text) {
  const rows = [];
  let row = [];
  let field = "";
  let quoted = false;
  let closed = false;
  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    if (quoted) {
      if (c === '"' && text[i + 1] === '"') {
        field += '"';
        i++;
      } else if (c === '"') {
        quoted = false;
        closed = true;
      } else {
        field += c;
      }
    } else if (c === ",") {
      row.push(field);
      field = "";
      closed = false;
    } else if (c === "\n" || (c === "\r" && text[i + 1] === "\n")) {
      if (c === "\r") i++;
      row.push(field);
      rows.push(row);
      row = [];
      field = "";
      closed = false;
    } else if (closed) {
      throw new Error(`text after closing quote at offset ${i}`);
    } else if (c === '"' && field === "") {
      quoted = true;
    } else if (c === '"') {
      throw new Error(`bare quote at offset ${i}`);
    } else {
      field += c;
    }
  }
  if (quoted) throw new Error("missing closing quote");
  if (field !== "" || closed || row.length > 0) {
    row.push(field);
    rows.push(row);
  }
  return rows;
}

function formatField(value) {
  return /[",\r\n]/.test(value) ? `"${value.replaceAll('"', '""')}"` : value;
}

function formatCsv(rows) {
  return rows.map((row) => row.map(formatField).join(",") + "\r\n").join("");
}

const text = 'id,name,note\r\n7,"Smith, Ann","said ""hi""\r\nand left"\r\n8,Bo,\r\n';
const rows = parseCsv(text);
console.log(rows);
console.log(JSON.stringify(formatCsv(rows)));
console.log(formatCsv(rows) === text);
console.log(parseCsv("a,b\n1,2"));
for (const bad of ['7,Sm"ith\n', '7,"Smith"x\n', '7,"Smith']) {
  try {
    parseCsv(bad);
  } catch (error) {
    console.log(error.message);
  }
}
Output
[
  [ 'id', 'name', 'note' ],
  [ '7', 'Smith, Ann', 'said "hi"\r\nand left' ],
  [ '8', 'Bo', '' ]
]
"id,name,note\r\n7,\"Smith, Ann\",\"said \"\"hi\"\"\r\nand left\"\r\n8,Bo,\r\n"
true
[ [ 'a', 'b' ], [ '1', '2' ] ]
bare quote at offset 4
text after closing quote at offset 9
missing closing quote
  • Verdict: idiom. JavaScript has no CSV parser in the language or in Node.js. The function parseCsv is a short state machine for RFC 4180. It accepts CRLF and LF row ends, and it rejects a bare quote, text after a closing quote and a missing closing quote.
  • Each field is a string. The program must convert numbers and dates itself.
TypeScriptGitHub
type Row = string[];

function parseCsv(text: string): Row[] {
  const rows: Row[] = [];
  let row: Row = [];
  let field = "";
  let quoted = false;
  let closed = false;
  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    if (quoted) {
      if (c === '"' && text[i + 1] === '"') {
        field += '"';
        i++;
      } else if (c === '"') {
        quoted = false;
        closed = true;
      } else {
        field += c;
      }
    } else if (c === ",") {
      row.push(field);
      field = "";
      closed = false;
    } else if (c === "\n" || (c === "\r" && text[i + 1] === "\n")) {
      if (c === "\r") i++;
      row.push(field);
      rows.push(row);
      row = [];
      field = "";
      closed = false;
    } else if (closed) {
      throw new Error(`text after closing quote at offset ${i}`);
    } else if (c === '"' && field === "") {
      quoted = true;
    } else if (c === '"') {
      throw new Error(`bare quote at offset ${i}`);
    } else {
      field += c;
    }
  }
  if (quoted) throw new Error("missing closing quote");
  if (field !== "" || closed || row.length > 0) {
    row.push(field);
    rows.push(row);
  }
  return rows;
}

interface Payment {
  zip: string;
  city: string;
  amount: number;
}

function toPayments(rows: Row[]): Payment[] {
  const [header, ...body] = rows;
  return body.map((fields, index) => {
    if (fields.length !== header.length) {
      throw new Error(`row ${index + 2}: ${fields.length} fields, expected ${header.length}`);
    }
    const amount = Number(fields[header.indexOf("amount")]);
    if (Number.isNaN(amount)) throw new Error(`row ${index + 2}: amount is not a number`);
    return { zip: fields[header.indexOf("zip")], city: fields[header.indexOf("city")], amount };
  });
}

const text = 'zip,city,amount\r\n02134,Boston,12.50\r\n10001,"New York, NY",3\r\n';
console.log(toPayments(parseCsv(text)));
for (const bad of ["zip,city,amount\r\n02134,Boston\r\n", "zip,city,amount\r\n02134,Boston,ten\r\n"]) {
  try {
    toPayments(parseCsv(bad));
  } catch (error) {
    console.log((error as Error).message);
  }
}
Output
[
  { zip: '02134', city: 'Boston', amount: 12.5 },
  { zip: '10001', city: 'New York, NY', amount: 3 }
]
row 2: 2 fields, expected 3
row 2: amount is not a number
  • Verdict: idiom. TypeScript has no CSV parser, and neither does JavaScript. The function parseCsv is the same state machine as in the JavaScript example, with types.
  • The types of TypeScript do not check the data at run time. The function toPayments checks the field count and converts amount by hand. The ZIP code stays a string, so its leading zero stays.
package main

import (
	"encoding/csv"
	"fmt"
	"os"
	"strings"
)

func main() {
	text := "id,name,note\r\n7,\"Smith, Ann\",\"said \"\"hi\"\"\r\nand left\"\r\n\r\n8,Bo,\r\n"
	records, err := csv.NewReader(strings.NewReader(text)).ReadAll()
	fmt.Println(err)
	for _, record := range records {
		fmt.Printf("%q\n", record)
	}

	bom, _ := csv.NewReader(strings.NewReader("\ufeffzip,city\n02134,Boston\n")).Read()
	fmt.Printf("%q\n", bom)

	writer := csv.NewWriter(os.Stdout)
	writer.Write([]string{"7", "Smith, Ann", "said \"hi\""})
	writer.Write([]string{"8", " Bo", ""})
	writer.Flush()

	var crlf strings.Builder
	w := csv.NewWriter(&crlf)
	w.UseCRLF = true
	w.Write([]string{"a", "b"})
	w.Flush()
	fmt.Printf("%q\n", crlf.String())
}
Output
<nil>
["id" "name" "note"]
["7" "Smith, Ann" "said \"hi\"\nand left"]
["8" "Bo" ""]
["\ufeffzip" "city"]
7,"Smith, Ann","said ""hi"""
8," Bo",
"a,b\r\n"
package main

import (
	"encoding/csv"
	"errors"
	"fmt"
	"strings"
)

func main() {
	ragged := csv.NewReader(strings.NewReader("a,b\n1,2,3\n"))
	_, err := ragged.ReadAll()
	fmt.Println(err, errors.Is(err, csv.ErrFieldCount))

	loose := csv.NewReader(strings.NewReader("a,b\n1,2,3\n"))
	loose.FieldsPerRecord = -1
	all, _ := loose.ReadAll()
	fmt.Println(all)

	for _, input := range []string{"7,Sm\"ith\n", "7,\"Smith\" Ann\n"} {
		_, err := csv.NewReader(strings.NewReader(input)).Read()
		fmt.Println(err)
		lazy := csv.NewReader(strings.NewReader(input))
		lazy.LazyQuotes = true
		record, err := lazy.Read()
		fmt.Printf("%q %v\n", record, err)
	}
}
Output
record on line 2: wrong number of fields true
[[a b] [1 2 3]]
parse error on line 1, column 5: bare " in non-quoted-field
["7" "Sm\"ith"] <nil>
parse error on line 1, column 9: extraneous or missing " in quoted-field
["7" "Smith\" Ann\n"] <nil>
  • Verdict: stdlib. The package encoding/csv has Reader and Writer. It follows RFC 4180, but Writer ends lines with LF unless UseCRLF is true.
  • The reader removes a CR before a newline, also inside a quoted field. It skips blank lines. It does not remove a BOM.
  • The reader rejects a bare quote and a ragged row by default. FieldsPerRecord = -1 turns off the field count check.
  • LazyQuotes accepts bad quotes, but the result can be wrong. In the second input, the field takes the rest of the line, with the newline.
RustGitHub
use serde::Deserialize;

#[derive(Deserialize)]
struct Payment {
    id: u32,
    name: String,
    amount: f64,
}

fn main() {
    let text = "id,name,amount\r\n7,\"Smith, Ann\",12.50\r\n8,Bo,3\r\n9,Cy,ten\r\n";
    let mut reader = csv::Reader::from_reader(text.as_bytes());
    for row in reader.deserialize::<Payment>() {
        match row {
            Ok(p) => println!("{} {:?} {}", p.id, p.name, p.amount),
            Err(e) => println!("error: {}", e),
        }
    }

    let bom = "\u{feff}zip,city\n02134,Boston\n";
    let mut reader = csv::Reader::from_reader(bom.as_bytes());
    println!("{:?}", reader.headers().unwrap());
}
Output
7 "Smith, Ann" 12.5
8 "Bo" 3
error: CSV deserialize error: record 3 (line: 3, byte: 45): field 2: invalid float literal
StringRecord(["zip", "city"])
fn main() {
    let ragged = "a,b\n1,2,3\n";
    let mut reader = csv::Reader::from_reader(ragged.as_bytes());
    for row in reader.records() {
        match row {
            Ok(r) => println!("{:?}", r),
            Err(e) => println!("error: {}", e),
        }
    }
    let mut reader = csv::ReaderBuilder::new()
        .flexible(true)
        .from_reader(ragged.as_bytes());
    for row in reader.records() {
        println!("{:?}", row.unwrap());
    }

    let mut writer = csv::Writer::from_writer(vec![]);
    writer.write_record(["7", "Smith, Ann", "said \"hi\""]).unwrap();
    writer.write_record(["8", " Bo", ""]).unwrap();
    println!("{:?}", String::from_utf8(writer.into_inner().unwrap()).unwrap());

    let mut writer = csv::WriterBuilder::new()
        .terminator(csv::Terminator::CRLF)
        .from_writer(vec![]);
    writer.write_record(["a", "b"]).unwrap();
    println!("{:?}", String::from_utf8(writer.into_inner().unwrap()).unwrap());
}
Output
error: CSV error: record 1 (line: 2, byte: 4): found record with 3 fields, but the previous record has 2 fields
StringRecord(["1", "2", "3"])
"7,\"Smith, Ann\",\"said \"\"hi\"\"\"\n8, Bo,\n"
"a,b\r\n"
  • Verdict: library. The Rust standard library has no CSV. The examples use the csv crate 1.4.0 with serde 1.0.229 and the derive feature.
  • Reader treats the first row as a header by default, and deserialize maps each row to a struct by the header names. A field that does not parse as its type gives an error for that row only.
  • A row with a different field count is an error (UnequalLengths) unless the reader is flexible.
  • Writer ends lines with \n by default. Terminator::CRLF gives the line end of RFC 4180. In this run, the reader removed the BOM from the header.
CREATE TABLE payment (id INTEGER, name TEXT, note TEXT);
INSERT INTO payment VALUES (7, 'Smith, Ann', 'said "hi"'), (8, 'Bo', NULL), (9, 'Cy', '');
.headers on
.mode csv
SELECT * FROM payment;
Output
id,name,note
7,"Smith, Ann","said ""hi"""
8,Bo,
9,Cy,""
  • Verdict: idiom. The SQL standard has no CSV functions. The SQLite shell has the dot command .mode csv for output and .import --csv for input, and PostgreSQL has COPY ... (FORMAT csv).
  • SQLite writes the CSV of RFC 4180, with CRLF line ends and quotes only where they are needed.
  • The NULL in row 8 becomes an empty field, and the empty string in row 9 becomes "". CSV has no other way to tell the two values apart.

Versions

CSV has no version number. The documents below describe it or the media type.

Document Date Status Content
PEP 305 January 2003 Python Enhancement Proposal, Final the csv module and its dialects5
RFC 4180 October 2005 Informational the common format; registers text/csv with the parameters charset and header1
RFC 7111 January 2014 Informational; updates RFC 4180 fragment identifiers for text/csv; UTF-8 is the default charset3
CSVW tabular data model December 2015 W3C Recommendation a model for tables, a CSV syntax that allows LF, and a parse algorithm with dialect flags4

RFC 7111

RFC 7111 defines fragment identifiers for text/csv. A URI can point to one row, one column, one cell or a range. For example, #row=5-7 selects rows 5 to 7, #col=2 selects the second column, and #cell=4,1 selects the cell in row 4 and column 1. Rows and columns start at 1.3 The scheme row selects records, not lines of text.3

RFC 7111 also changes the registration of text/csv. It follows RFC 6657: the parameter charset SHOULD be used, and if it is absent, UTF-8 SHOULD be assumed.32 RFC 4180 had said that the common usage was US-ASCII.1

CSV on the Web

The W3C model for tabular data describes a CSV syntax for publishers.4 It differs from RFC 4180 in one point: rows can end with LF as well as CRLF. Each file that follows RFC 4180 also follows this syntax. The model gives these rules:

  • The file should be in UTF-8, in Unicode Normalization Form C. Another encoding should be named in the parameter charset.
  • Each line should have the same number of values.
  • There should be no whitespace before or after the double quotes of a field.
  • The first line should be a header. A file with no header should say header=absent in the media type.

The model also defines an algorithm to parse CSV files that do not follow these rules. Flags control it, such as delimiter, encoding, lineTerminators, skipRows and trim. The default delimiter is ,, the default encoding is UTF-8, and both CRLF and LF end a row by default.4 Metadata can give each column a name and a datatype, and a dialect description can set the flags. Other specifications, csv2json and csv2rdf, define the conversion of a table to JSON and RDF.4

Pitfalls

  • The delimiter depends on the locale. Excel uses the list separator of the system. Where the decimal separator is a comma, Excel uses a semicolon as the list separator.12 A file from such a system has the text Tea;3,50. Commons CSV says that "the actual value delimiter used by Excel is locale-dependent".9 Ask for the delimiter, or detect it. Python has csv.Sniffer to guess the dialect from a sample.6
  • The byte order mark. A UTF-8 file can start with a byte order mark (BOM), the bytes EF BB BF. A reader that decodes the file as plain UTF-8 makes the BOM part of the first header name. Then the name is \ufeffzip and not zip, and a lookup of zip fails. Python reads it correctly with the encoding utf-8-sig. In the example runs, Go keeps the BOM and the Rust csv crate removes it.
  • LF line ends. RFC 4180 uses CRLF. The CSVW model also allows LF, because LF is important on platforms other than Windows.4 The readers of Python, Go and Rust accept both.678 Writers differ. The Python writer uses CRLF, but the Go writer and the Rust writer use LF by default.678
  • A line break inside a field. A quoted field can hold a line break, so a record can take more than one line. A tool that works line by line counts lines and not records. It can cut a record in two.
  • Leading zeros, dates and gene names. Excel uses its default data formats when it opens a .csv file. Microsoft gives a column of numbers with leading zeros as a case for the Import Text Wizard, which can import the column as text and keep the zeros.12 The CSVW model reports that Excel for Mac 2011 detects dates in the form YYYY-MM-DD and formats them again.4 A study of the scientific literature found that Excel changes some gene names to dates and to floating-point numbers. About one fifth of the papers with supplementary gene lists in Excel files had such errors.13
  • CSV injection. A spreadsheet reads a cell that starts with = as a formula. OWASP lists =, +, -, @, tab, carriage return and line feed as the dangerous first characters. The risk comes when a website puts untrusted input into a CSV file. A crafted formula can attack the computer of the user through a flaw in the spreadsheet program, or copy data out of the spreadsheet.11 OWASP advises to put a single quote before such a cell, to put each cell in double quotes, and to double each double quote in a cell. It warns that Excel can lose this escape when a user saves the file and opens it again.11
  • Ragged rows. A row can have more or fewer fields than the header. Go and the Rust csv crate return an error by default. Python DictReader fills missing fields with None.786 In the example run, Commons CSV returns the row as it is. Check the field count when the data comes from outside.
  • Bad quotes. A quote inside an unquoted field, or text after the closing quote, breaks rule 5 or rule 7. Go returns ErrBareQuote or ErrQuote.7 The Python reader accepts both by default. With strict=True, Python rejects text after a closing quote.6 A lenient mode, such as LazyQuotes in Go, can merge the rest of the line into one field.
  • No declared encoding. A CSV file does not say what its encoding is. Python decodes a file with the system default encoding unless the program gives encoding=.6 The CSVW model reports that Excel for Mac 2011 with an English locale writes Windows-1252 and changes other characters to underscores.4 Google Sheets writes UTF-8 with no BOM.4
  • A trailing empty line. A blank line at the end, or between records, is an empty record under the grammar. Go skips blank lines.7 The Commons CSV format DEFAULT allows empty lines, but the format RFC4180 does not ignore them.9
  • Whitespace around fields. RFC 4180 says that spaces are part of a field.1 TextFieldParser in .NET removes them by default, and the CSVW parser trims cells by default.104 So the field Bo can come back as Bo or as Bo, and the result depends on the reader.
  • NULL and the empty string. CSV has no null value. The PostgreSQL documentation says that "the CSV format has no standard way to distinguish a NULL value from an empty string". PostgreSQL COPY writes NULL as an empty field with no quotes, and an empty string as "".15 The SQLite example does the same.

Tools and libraries

Language Verdict Read and write
Python stdlib csv.reader, csv.writer, csv.DictReader, csv.DictWriter6
Go stdlib encoding/csv, csv.NewReader, csv.NewWriter7
C# stdlib TextFieldParser reads; no writer in the base library10
Rust library the csv crate, Reader and Writer, with serde8
Java library Apache Commons CSV, CSVFormat, CSVParser, CSVPrinter9
JavaScript, TypeScript idiom a short parser; no CSV API in the language or in Node.js
SQL idiom SQLite shell .mode csv and .import --csv; PostgreSQL COPY ... (FORMAT csv)1415
PowerShell stdlib Import-Csv, Export-Csv, ConvertFrom-Csv, ConvertTo-Csv16

The SQLite shell reads a CSV file into a table with .import --csv. If the table does not exist, the first row gives the names of the columns. The option --skip 1 skips a header row when the table exists.14 The mode .mode csv writes the result of a query as CSV "per RFC 4180".14

PostgreSQL reads and writes CSV with the command COPY and the option FORMAT csv. Other options set the header, the quote character, the escape character and the columns that are always quoted. In CSV format, "all characters are significant", so the spaces around a value are part of it.15

PowerShell Import-Csv makes one object for each row, with one property for each column. The parameter Delimiter sets the delimiter, and the parameter UseCulture uses the list separator of the current culture. ConvertFrom-Csv does the same with strings from the pipeline.16

References

  1. Y. Shafranovich, RFC 4180: Common Format and MIME Type for Comma-Separated Values (CSV) Files, October 2005, the header; 1 Introduction; 2 Definition of the CSV Format; 3 MIME Type Registration of text/csv; 4 IANA Considerations
  2. IANA, Media type registration of text/csv, the whole template (registered by RFC 4180, last updated 2014-01-17)
  3. M. Hausenblas, E. Wilde, J. Tennison, RFC 7111: URI Fragment Identifiers for the text/csv Media Type, January 2014, the header; 2 Fragment Identification Methods; 3 Fragment Identification Syntax; 5.1 The text/csv media type
  4. J. Tennison, G. Kellogg (Eds.), Model for Tabular Data and Metadata on the Web, W3C Recommendation, 17 December 2015, the sections Best Practice CSV and Parsing Tabular Data; the appendix Existing Standards (RFC 4180, Excel, Google Spreadsheets)
  5. K. Altis, D. Cole, A. McNamara, S. Montanaro, C. Wells, PEP 305: CSV File API, created 26 January 2003, Abstract; Rationale; Managing Different Dialects
  6. The Python Standard Library, csv, Python 3.14, the introduction; Module Contents; Dialects and Formatting Parameters; Examples; footnote 1
  7. Go standard library, package encoding/csv, Overview; Variables (ErrBareQuote, ErrQuote, ErrFieldCount); type Reader; type Writer
  8. csv 1.4.0 documentation (Rust crate), ReaderBuilder (has_headers, flexible, terminator); WriterBuilder (terminator, quote_style)
  9. Apache Commons CSV, class CSVFormat, the predefined formats DEFAULT, EXCEL and RFC4180
  10. .NET API documentation, TextFieldParser class, Remarks; the properties TrimWhiteSpace, ErrorLine and ErrorLineNumber
  11. OWASP, CSV Injection, the description and the advice on how to escape cells
  12. Microsoft Support, Import or export text (.txt or .csv) files, Import a text file by opening it in Excel; Change the default list separator for saving files as text (.csv) in Excel
  13. M. Ziemann, Y. Eren, A. El-Osta, Gene name errors are widespread in the scientific literature, Genome Biology 17:177, 2016, the abstract
  14. SQLite, Command Line Shell For SQLite, 7.5 Importing files as CSV or other formats; 7.6 Export to CSV
  15. PostgreSQL 18 documentation, COPY, the section CSV Format
  16. PowerShell documentation, Import-Csv, the description and the parameters Delimiter, Encoding and UseCulture

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/WEWPMR/text.yaml