hayaliv

hayaliv / Hi! Python / Level 1

CSV

Read and write comma-separated tables with csv.reader, DictReader and DictWriter.

Hi! Python · Level 1: Files and data · Checked against the Python 3.12 documentation · Updated 2026-10-17

Think of it like this

A CSV file is like a paper register with columns. Each line is a row, and a comma separates the boxes on that row.

Where the analogy stops being true. On paper a box can hold anything, but in a CSV file a comma inside a box needs quoting, and by default everything you read back is text.

What to know

Example

import csv
import io

rows = [
    {"input": "Sure, Friday works", "label": "meeting_request"},
    {"input": "No thanks", "label": "not_interested"},
]
buf = io.StringIO()
writer = csv.DictWriter(buf, fieldnames=["input", "label"])
writer.writeheader()
writer.writerows(rows)
print(repr(buf.getvalue()))
buf.seek(0)
for row in csv.DictReader(buf):
    print(row["label"], "|", row["input"])
print(next(csv.reader(['a,"b,c",d'])))
print('a,"b,c",d'.split(","))

It prints:

'input,label\r\n"Sure, Friday works",meeting_request\r\nNo thanks,not_interested\r\n'
meeting_request | Sure, Friday works
not_interested | No thanks
['a', 'b,c', 'd']
['a', '"b', 'c"', 'd']

Predict, then check

1. What does this print?

import csv

print(list(csv.reader(['a,"b,c",d'])))
Show the answer
[['a', 'b,c', 'd']]

The quotes keep b,c together as one field, so the row has three fields.

2. What does this print?

import csv

row = next(csv.reader(["1,2"]))
print(row[0] + row[1])
Show the answer
12

Both fields are strings, so + joins them instead of adding numbers.

3. What does this print?

import csv

print([r["label"] for r in csv.DictReader(["input,label", "hi,x"])])
Show the answer
['x']

The first row names the fields, so the second row becomes {'input': 'hi', 'label': 'x'}.

Try it

Write labels_in(text). The text is CSV with a header row input,label. Return the list of label values, one per data row.

def labels_in(text):
    return []
Show a solution
import csv
import io

def labels_in(text):
    return [row["label"] for row in csv.DictReader(io.StringIO(text))]

Common mistake

If you open a real CSV file without newline="", the docs say newlines embedded inside quoted fields will not be interpreted correctly. They also say it should always be safe to specify it.

In a small-language-model project

Annotation tools and spreadsheets may export labelled replies as CSV. Reading with DictReader lets you rebuild {"input": ..., "label": ...} records, and remember that, by default, every value arrives as text.

Sources

Each quote below appears word for word on the cited page of the official Python documentation (version 3.12).

Step through this lesson in the Hi! Python desktop

← JSONL-style records: one JSON object per lineRegular expressions, the basics →