KKAIROS
Practical guideIllustrative4 min read

Python csv module: read and write rows with quoting rules

The csv module reads and writes rows with quoting rules that plain split cannot handle. Covers quoting and embedded commas with newline=''.

Published:

Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.

TE-50-A: csv module handles a comma inside quotes where split does not, and newline='' is the documented open mode

Setup for this run, inside a throwaway directory (mktemp -d):

printf 'a,"x,y"\n' > c.csv

Command:

python3 -c "import csv; rows=list(csv.reader(open('c.csv', newline='', encoding='utf-8'))); print(rows[0], len(rows[0])); print(open('c.csv', encoding='utf-8').read().strip().split(',')[1:])"

Recorded output:

['a', 'x,y'] 2
['"x', 'y"']

This run checks the exit status and records the output; it asserts no expected text.

Exit status: 0. This is the status recorded in the log for TE-50-A.

TE-50-B: csv.writer adds quotes around a field that has a comma or a quote mark, and doubles the quote mark

Setup for this run, inside a throwaway directory (mktemp -d):

cat > s.py <<'EOS'
import csv, sys
w = csv.writer(sys.stdout, lineterminator='\n')
w.writerow(['a', 'x,y', 'q"r'])
EOS

Command:

python3 s.py

Recorded output:

a,"x,y","q""r"

Exit status: 0. This status and the output match what was written before the run.

TE-50-C: expected non-zero exit: a csv reader with strict=True raises csv.Error on a quoted field that is not closed

Setup for this run, inside a throwaway directory (mktemp -d):

cat > s.py <<'EOS'
import csv
list(csv.reader(['a,"b'], strict=True))
EOS

Command:

python3 s.py

Recorded output: none, standard output was empty.

Standard error from the same run:

Traceback (most recent call last):
  File "/tmp/b26-4zcniowh/work/s.py", line 2, in <module>
    list(csv.reader(['a,"b'], strict=True))
_csv.Error: unexpected end of data

Exit status: 1. This status and the output match what was written before the run. The path in the traceback line is a temporary folder and differs on each machine and each run.

Reading the recorded output

By the setup, the line in c.csv is a,"x,y". The first output line shows the result of csv.reader on it: two fields, a and x,y, and the length 2. The comma inside the quotes stayed in the second field. The second line shows what split(',') gave for the same text, after the first piece was dropped with [1:]: the two pieces printed are '"x' and 'y"', as the output shows: ['"x', 'y"'], with the quote marks still attached. So split cut the quoted field in two.

TE-50-B: csv.writer wrote a, then x,y in quotes because it holds a comma, then q"r in quotes with the quote mark doubled. TE-50-C: the reader with strict=True stopped with exit status 1 on a quoted field that is not closed. The last line of standard error is _csv.Error: unexpected end of data.

Ad

Limits

Covers quoting and embedded commas with newline=''. Encoding and embedded newlines are outside this page.

Source

Evidence

Evidence table

| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-50-A | csv module handles a comma inside quotes where split does not, and newline='' is the documented open mode | 0 | PASS | 5e66f3407fde | | TE-50-B | csv.writer adds quotes around a field that has a comma or a quote mark, and doubles the quote mark | 0 | PASS | 50b49df1817d | | TE-50-C | expected non-zero exit: a csv reader with strict=True raises csv.Error on a quoted field that is not closed | 1 | PASS | 56658e641c8f |

Every row has a recorded log holding the setup commands, the command, stdout, stderr, exit status and the final directory state. The first 12 characters of the log's sha256 are in the table.

All full guides: All guides