Skip to the content

Project: expense log

Python · Unit 17: Files

The log stores one expense per row: the category and the amount. Later it is read with DictReader and added up.

writerows writes several rows at once: it takes a list of lists.

import csv
costs = [["power", 300], ["bread", 20]]
with open("log.csv", "w") as f:
    wr = csv.writer(f)
    wr.writerow(["kind", "amount"])
    wr.writerows(costs)
print(open("log.csv").read())

Prints

kind,amount
power,300
bread,20

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Complete the code

    Complete it to add up every amount in the file.

  2. 2. Write the code

    Write add_line(old, new). It already saves the lines of old into log.txt. Append the line new at the end using mode "a" and return the list of all the lines, with no breaks.

  3. 3. Write the code

    Write totals(costs). costs is a list of [category, amount] pairs that are already saved into log.csv. Read the file with DictReader and return a dictionary with the total of each category.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →