Project: expense log
Python · Unit 17: Files
- Full plan
- Python
- Project
- 3 exercises
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. Complete the code
Complete it to add up every amount in the file.
2. Write the code
Write
add_line(old, new). It already saves the lines ofoldintolog.txt. Append the linenewat the end using mode"a"and return the list of all the lines, with no breaks.3. Write the code
Write
totals(costs).costsis a list of[category, amount]pairs that are already saved intolog.csv. Read the file withDictReaderand return a dictionary with the total of each category.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.