Lesson 8 of 12
Structured learning draftRead CSV records without splitting them by hand
CSV files may contain commas inside quoted names. Use the standard CSV reader to handle the format, inspect the headers, and convert numeric fields explicitly before calculating a stock result from the records.
Learning objectives
- Read quoted CSV fields correctly.
- Use headers to identify columns.
- Convert numeric text before arithmetic.
Read CSV records without splitting them by hand: the working sequence
Trace the three stages of read csv records without splitting them by hand and compare them with the example.
The CSV fixture includes a quoted item name containing a comma.
DictReader creates records keyed by the header names.
int() turns the quantity field into a number for later checks.
DictReader reads the header row as field names. Its field values are strings, so quantity still needs conversion. StringIO provides a self-contained practice file without writing to your computer; real files should be opened with an explicit encoding and newline=''.
import csv
from io import StringIO
data = 'name,quantity\n"Pens, blue",12\nBooks,3\n'
reader = csv.DictReader(StringIO(data))
for row in reader:
print(row['name'], int(row['quantity']))Pens, blue 12
Books 3Try it, then change it
- Run the fixture and check that Pens, blue remains one name.
- Replace one quantity with 'many' and identify the failing record.
- Check reader.fieldnames before the loop and reject missing name or quantity columns.
Common mistakes
- Splitting each line on commas and breaking quoted fields.
- Adding CSV strings instead of numeric quantities.
- Ignoring unexpected or missing headers.
Practice activity
Apply the lesson
Create a four-record CSV fixture including one comma-containing name. Calculate its total quantity, then test a missing header and invalid quantity. Keep the changed example, its output and a short explanation of whether the result matched your prediction.
How to check your work
- Write down the expected result before running or submitting your work.
- Try a normal example, an empty or missing input, and a boundary case where the rule changes.
- Compare the actual result with your prediction. Record the smallest example that explains a difference.
- Explain one change you made and why it improved the result. Save your evidence in the lesson notes.
When you get stuck · Python
The script stops with a traceback or gives an unexpected value.
- Find the cause
- Read the exception type and message on the last line, then find the referenced line in your own file. Compare the value and type of each input with what that operation expects.
- Try this
- Reduce the failing case to a few lines. Check variable spelling, numeric conversion and file paths. Handle only the exception you expect; do not hide an unknown error with a broad except block.
- Check the fix
- Run the corrected case and a deliberately invalid input. The valid input produces the expected result; the invalid input gives a clear message or raises the documented exception.
Use this course-wide example when it fits your task. For a different failure, record the input, expected result, actual result and smallest steps that reproduce it.
Watch, pause, practise
Free video lessons
Choose the chapter that matches your task. Videos open on the original provider’s site; playback uses additional data.
CS50: programming with Python
Choose the lecture on functions, loops, exceptions, tests or files that matches your current task.
Try it yourself: Before running an example, predict its output. Try an empty input and record how the program behaves.
Source checked 2026-10-07 · Free learning material; optional certificates may cost extra.Check your understanding
Why should you avoid line.split(',') for this fixture?
Lesson summary
- Use a CSV parser for CSV syntax.
- Headers describe the meaning of each field.
- Parsing the file does not validate the records.
Sources and further reading
- csv: CSV file reading and writingPython Software Foundation - accessed 2026-10-07
- Python language referencePython Software Foundation - accessed 2026-10-07
Personal study note
Your notes
Keep the input, expected result, actual result and what you changed. Save before leaving this lesson. Download a copy to keep it outside this browser.