76. Total a CSV column
A CSV file holds a table as text: one row per line, the fields separated by commas, the first line naming the
columns. A field that itself contains a comma is put in double quotes, as in "Paris, France".
Write a function column_total(csv_text, column) that takes the contents of a CSV file as a string and the name of a
column, and returns the total of the numbers in that column as a float:
- The first line is the header: it names the columns. Every line after it is a row of data.
- Quoted fields are one field, commas and all: splitting each line at its commas gets them wrong. Python's
csvmodule reads them properly. - An empty cell counts as 0.
- A file with a header and no rows has a total of
0.0.
The examples write the file's text as Python strings, with \n at the end of each line.
Example 1
csv_text = "name,amount\nAnn,10\nBob,5.5\n",
column = "amount"15.5Example 2
csv_text = "city,people\n"
"\"Paris, France\",3\n"
"\"Austin, Texas\",4\n",
column = "people"7.0Example 3
csv_text = "item,qty,price\npen,2,1.5\nink,,3\n",
column = "qty"2.0Constraints
csv_texthas 1 to 50 lines and ends with a line break; no field contains a line break.columnis one of the names in the header, and every row has a field for every column.- Every non-empty field of that column is a number, such as
12,-3or4.75.
Submit also runs 7 more tests you can't see.
Practises Reading and Writing Files (lesson 23).
import csv, thencsv.reader(csv_text.splitlines())gives each line as a list of fields, with quoted commas handled.- The first row is the header:
header = next(rows)takes it, andheader.index(column)tells you which position to read in every other row. - Add
float(row[at])for each remaining row, skipping empty strings:float("")raises an error.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def column_total(csv_text, column):
"""Add up one column of a CSV file's text.
csv_text: str, the file's contents, header line first
column: str, the name of the column to add up
Returns: float, the total of that column, empty cells
counting as 0
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.