OpenViSTAI · Agents · Blockchain · Crypto
Menu

OPENVIST LEARN · FREE LESSONS

CSV rows, headers and quoted fields

Read tabular text without splitting it incorrectly at every comma.

Lesson 17 of 22 · About 20 minutes · Beginner · English

By the end of this lesson

Use DictReader and check the expected header.

Before you start

  • Python 3.12 or a compatible newer Python 3 interpreter; no external packages.
  • Complete lesson 16 in this route, or be comfortable with its examples.

Three words to know

CSV
A family of text-based table formats with delimited fields.
Header
A row naming the columns.
Dialect
Choices such as delimiter and quoting rules.

1. Let the CSV parser handle quoting

A comma inside a quoted field is part of the value, not a column boundary. csv.DictReader uses the header as dictionary keys. StringIO lets this small example read a string as a text file, so it does not need any setup file.

Read a name containing a commaPYTHON · save as lesson.py, then run with your interpreter
import csv
import io

text = 'name,status\n"Read, then test",open\nShip,closed\n'
reader = csv.DictReader(io.StringIO(text, newline=""))
if reader.fieldnames != ["name", "status"]:
    raise ValueError("unexpected header")
for row in reader:
    print(row["name"], row["status"])
What you should see · example output
Read, then test open
Ship closed

2. Decide what a valid table means

A successful parse does not establish unique headers, equal row lengths or valid business values. DictReader can represent missing fields as None and extra fields under a None key. Decide whether to reject those cases, and validate headers before trusting the resulting dictionaries. When opening a real CSV file, use newline="" and an explicit encoding.

3. Keep spreadsheet behaviour separate

CSV stores text fields, not a safe spreadsheet workbook. Spreadsheet applications may interpret cells beginning with formula characters. This reading exercise does not sanitise exports for spreadsheets. If you later export untrusted values, choose and document the target application’s precautions rather than assuming quoting disables formulas.

YOUR TURN

A small check before you continue

Why is line.split(",") wrong for the first data row in this example?

Show a suggested answer

It splits the comma inside the quoted name and invents a third field. The CSV parser respects quotes and produces two named fields.

Sources and scope

Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.