CSV
Python · Unit 17: Files
- Full plan
- Python
- 9 exercises
A CSV is a text file where every line is a row and the columns are separated by commas.
import csv brings the tools to build it right: csv.writer(f) sets it up and writerow writes one row from a list.
import csv
with open("v.csv", "w") as f:
wr = csv.writer(f)
wr.writerow(["fruit", "kilos"])
wr.writerow(["pear", 3])
print(open("v.csv").read())Prints
fruit,kilos pear,3
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Predict the output
What does this code print?
3. Complete the code
Complete it to walk over the rows of the file.
4. Predict the output
What does this code print?
5. Complete the code
Complete it to show the kilos of each row.
6. Find the bug
This program should add up the kilos and show 5. Which line has the bug?
7. Put the lines in order
Put the lines in order to save the sales table and show it.
8. Multiple choice
What does
csv.DictReadergive you that splitting each line withsplit(",")doesn't?9. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.