Processing CSV data
Read a CSV file with the csv module and total and average its converted numbers by group with a dictionary.
It opens on
In a CSV file, a row reads Ana,books,120. When Python reads it, is 120 a number you can add?
Why it matters
CSV is the plain format that spreadsheets, sensors and websites export, and a first real data task is almost always read rows, convert fields, and summarise by group; this read, convert, accumulate pattern is a standard exam and project question.
Good to know first
- Reading and writing files: with open(name) as f reads a file line by line
- Dictionaries: d.get(key, 0) + x adds to a running total per key
- Exceptions: int raises ValueError on text that is not a number
Step by step
Reading rows
Read a CSV file with csv.reader, skip the header, and convert a text field to a number to total a column.
That answers the opening question. The csv module reads every field as text, and the program decides which fields are numbers.
A common mix-up
Numbers in a CSV file come in as numbers.
In fact: Every field is a string until the program converts it with int or float.
Totals by group
Use DictReader and two dictionaries to total and count sales by department, then compute each department's average.
Ana's row adds 120 to books. Ben's adds 80 to toys. Cara's adds 95 to books, making 215, with a count of 2.
A common mix-up
An average by group needs a separate loop over the file for each group.
In fact: One pass with a total and a count per key does every group at once.
Bad rows
Explain the crash from not skipping a header, and skip a bad row with try and except while keeping a record of it.
Wrapping the conversion in try lets the loop skip that row and carry on.
skipping a bad row
A common mix-up
A try with except that just says pass is the cleanest way to handle bad rows.
In fact: It hides how much data was dropped; always report the rows skipped.
Try it
Count how many rows have sales of at least 100.Answer
2, Ana with 120 and Eli with 150
Hint: Compare int(sales) >= 100
Which department has the highest average, and which the highest total?Answer
Games, 150.0, for the average; books, 215, for the total
Hint: Games has only one row
A file has a row with an empty sales field. What does int("") do, and does the try loop survive it?Answer
It raises ValueError, invalid literal, and the loop catches it and skips that row
Hint: The empty string is not a number
The run printed the first row as ['Ana', 'books', '120'] and the type of its last field as str. Can 120 be added as it is?Answer
No; it is the string '120', and adding strings joins them, '120' + '95' gives '12095', so it must be converted with int.
After Dev's and Eli's rows, what are the totals and counts for toys and games?Answer
Toys 140 from 80 + 60, count 2; games 150, count 1.
