Skip to the content

CSV

Python · Unit 17: Files

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. 1. Predict the output

    What does this code print?

  2. 2. Predict the output

    What does this code print?

  3. 3. Complete the code

    Complete it to walk over the rows of the file.

  4. 4. Predict the output

    What does this code print?

  5. 5. Complete the code

    Complete it to show the kilos of each row.

  6. 6. Find the bug

    This program should add up the kilos and show 5. Which line has the bug?

  7. 7. Put the lines in order

    Put the lines in order to save the sales table and show it.

  8. 8. Multiple choice

    What does csv.DictReader give you that splitting each line with split(",") doesn't?

  9. 9. Predict the output

    What does this code print?

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 →