15
Lesson 37 of 44

CSV and JSON files

CSV and JSON are the two most widely used data formats in practice. In this lesson you will learn how to read and write CSV files with the csv module, including headers and fields with commas, and how to convert Python data to JSON and back with the json module. You will also learn to handle errors and to choose the right format, with practical exercises.

  • 5 theory articles
  • 10 practice exercises
Start lesson

Fundamentals concepts 5

CSV files: reader and writer

CSV (*Comma-Separated Values*) is the simplest format to store tables of data: each line is a row and the values of each row are…

Theory
Read more

DictReader and DictWriter

Accessing columns by position ( row[2] ) is awkward and error-prone: if you add a column, all the numbers change. DictReader and…

Theory
Read more

JSON: dumps and loads

JSON (*JavaScript Object Notation*) is the standard format for exchanging data between programs, especially on the internet: web…

Theory
Read more

JSON in files, nested data and errors

To save JSON in a file and read it later you use json.dump and json.load , without the final "s": they work directly with files…

Theory
Read more

CSV or JSON: which to choose and good practices

Both formats serve to store data as text, but they solve different problems. Choosing the format well makes the rest of the…

Theory
Read more

Practice exercises 10

Column total

Create a Python program that reads lines in CSV format and adds up one of their columns with the csv module.

Exercise Easy
Solve it

Quoted fields

Create a Python program that reads CSV lines whose fields may contain commas, thanks to the quotes.

Exercise Medium
Solve it

Filter rows by city

Create a Python program that reads a CSV with a header and shows the people of a city using csv.DictReader .

Exercise Medium
Solve it

Writing a CSV

Create a Python program that generates a CSV with csv.writer , letting the module take care of the quotes.

Exercise Medium
Solve it

Reading a JSON object

Create a Python program that reads a JSON object and shows some of its data with the json module.

Exercise Easy
Solve it

Order total

Create a Python program that calculates the total of an order stored as a JSON list.

Exercise Medium
Solve it

Creating a JSON

Create a Python program that builds a dictionary and converts it into JSON text with json.dumps .

Exercise Medium
Solve it

Most populated city

Create a Python program that analyzes a JSON with nested data.

Exercise Medium
Solve it

Validating JSON

Create a Python program that checks whether a text is valid JSON, catching the error raised by json.loads .

Exercise Medium
Solve it

From CSV to JSON

Create a Python program that converts data in CSV format to JSON.

Exercise Medium
Solve it