TactivergeLite

Lite / Intelligent Robotic Systems / Week 3

From CSV file to records you can query

A test rig writes a CSV with a header row and 2,000 lines. How do you ask 'which runs drew more than 1.5 A?' without counting columns by hand?

About 40 min · 3 goals · Checked by automated tests · Full interactive version

Why should I care?

Most engineering data arrives as text tables: test-rig logs, inventories, sensor exports. Turning each row into a dictionary keyed by column name makes every later question readable and robust to someone adding a column.

Predict

csv.DictReader reads the row 'run,current_a' / '3,1.72'. What is type(row['current_a'])?

  1. float
  2. int
  3. str
  4. dict
Guess first, then reveal

str. CSV is text; the reader never guesses types. You must convert with float(row['current_a']), and decide what to do if the text is empty or not a number.

Discover

In the Code Lab, paste the worked example. Run it, then add a row with an empty current and one with 'n/a'. Make the loader skip bad rows but count them, and print how many were skipped.

What the interactive shows (text version)

The Code Lab activity can be done on paper: from the five-row log, motor A has currents 1.20 and 1.31 (mean 1.255 A) and motor B has 1.72 and 1.66 (mean 1.69 A); run 4 has an empty current and is skipped and counted.

You can also open the interactive on the full site when you have a faster connection.

Watch (optional)

Watch for: Watch how DictReader uses the header row as keys, and how the writer produces a CSV from dictionaries.

Reads and writes real CSV files with csv.reader and csv.DictReader, the same tools you use on a sensor log.

“Python Tutorial: CSV Module - How to Read, Parse, and Write CSV Files” by Corey Schafer (opens YouTube; streaming video uses a lot of data)

The video is optional. Everything you need is in this lesson's text.

Understand

Rows as dictionaries

csv.DictReader uses the header row as keys, so each row becomes {"run": "3", "motor": "B", "current_a": "1.72"}. Code that says row["current_a"] keeps working if someone inserts a new column; code that says row[2] silently reads the wrong one.

Text in, numbers out, carefully

Every field is a string. Convert with int() or float() inside a try block, and decide a policy for bad values: skip and count them, or stop with an error naming the line. Never let a bad row quietly become 0.

Group with a dictionary

To summarise by category, build a dict of lists: by_motor.setdefault(row["motor"], []).append(current). Then each key's list can be averaged or counted. Dictionaries are the natural shape for 'one answer per name'.

Explain it another way

Intuitive

A CSV is a spreadsheet saved as plain text. DictReader is like reading each row while keeping your finger on the header, so you always know which number is which.

Technical

csv handles quoting and commas inside fields, which a naive line.split(",") gets wrong. io.StringIO lets you test a loader on a string instead of a real file. Opening files with newline="" is the documented way to let the csv module handle line endings.

Applied

Test engineers often keep raw rig logs untouched and write loaders that report how many rows were rejected and why, so the cleaning step is visible in the final report.

Worked example 1

Load a motor test log, skip bad rows, and average current per motor.

import csv
import io

LOG = """run,motor,current_a
1,A,1.20
2,B,1.72
3,A,1.31
4,B,
5,B,1.66
"""


def load_runs(text):
    """Return (records, skipped). Each record has run (int), motor (str), current_a (float)."""
    records, skipped = [], 0
    for row in csv.DictReader(io.StringIO(text)):
        try:
            records.append({"run": int(row["run"]), "motor": row["motor"], "current_a": float(row["current_a"])})
        except ValueError:
            skipped += 1
    return records, skipped


runs, bad = load_runs(LOG)
by_motor = {}
for r in runs:
    by_motor.setdefault(r["motor"], []).append(r["current_a"])
for motor, values in sorted(by_motor.items()):
    print(motor, round(sum(values) / len(values), 3), len(values))
print("skipped", bad)
# A 1.255 2
# B 1.69 2
# skipped 1

Common mix-ups

Practice

Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.

Practice 1. row = {'run': '4', 'current_a': '1.5'} from DictReader. What does row['run'] + 1 do?

A

Practice 3. Some rows have current 'n/a'. Which policy is best for an engineering report?
Practice 4. Which line adds current to a per-motor list, creating the list the first time a motor appears?

Apply it

Write a loader for a part inventory CSV (part_no, description, qty, mass_g) that returns a list of dicts and a count of rejected rows. Use it to answer: which parts have qty below 10, and what is the total mass in stock in kg? Test the loader on a string containing at least one bad row.

Reflect

Why is it important that your report says how many rows were skipped?

Write your answer on paper or in your own notes. Lite never stores what you write.

Go further

← Slice, filter, transform: lists at speedModule check: the stores audit →