50 XP

76. Total a CSV column

Intermediate parsing strings

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 csv module 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

Inputcsv_text = "name,amount\nAnn,10\nBob,5.5\n", column = "amount"
Output15.5
Explanation10 + 5.5 from the amount column.

Example 2

Inputcsv_text = "city,people\n" "\"Paris, France\",3\n" "\"Austin, Texas\",4\n", column = "people"
Output7.0
ExplanationEach quoted city is one field.

Example 3

Inputcsv_text = "item,qty,price\npen,2,1.5\nink,,3\n", column = "qty"
Output2.0
ExplanationThe empty qty for ink counts as 0.

Constraints

  • csv_text has 1 to 50 lines and ends with a line break; no field contains a line break.
  • column is 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, -3 or 4.75.

Submit also runs 7 more tests you can't see.

Practises Reading and Writing Files (lesson 23).

Code
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