Lessons 6–10 · About 60 min per lesson

Files, CSV and JSON

Read and write structured files and check that fields survive each step.

Lesson breakdown

  1. Lesson 6

    Read and write UTF-8 text using with.

  2. Lesson 7

    Read named columns with csv.DictReader.

  3. Lesson 8

    Convert numeric fields and verify parsing of commas and quotes.

  4. Lesson 9

    Save and restore nested data with json.dump and json.load.

  5. Lesson 10

    Convert a file and check an empty table and non-ASCII characters.

Worked example

Convert CSV with header name,minutes and row "Lin, Mei",15 to JSON.

How to solve it

The CSV reader preserves the comma in the name. Convert minutes to an integer and write [{"name":"Lin, Mei","minutes":15}].

Assignment

Write a CSV-to-JSON converter that keeps name and numeric minutes.

Check your result

Keep a quoted name containing a comma intact, write [] for a header-only file, and read a Chinese name back correctly.