Easy Python CSV Tutorial

Sometimes we want persistently store data from our Python programs that can’t be represented in a simple 1 dimensional list.

This data has 2 dimensions, and in reality we are storing table data.

This data needs to stored to and read from a CSV file.

This table above can be stored in a Comma Separated Values file, that might look a bit like this:

To read from and write to these files, it’s easiest to use the csv module!

Reading from CSV Files

Reading from a csv file is easy….

Let’s suppose we haver a csv file that looks like this:

scores.csv

All we need it to write a program that:

  • Opens a file connection
  • Starts the CSV reader engine
  • Loads all of the stored file data into a Python 2D list

myreader.py

The result is that your program now contains a list called scores that contains the values loaded in. Here is what it looks like in Python:

scorelist = [[‘bob’, ‘jones’, ’20’], [‘fred’, ‘wilson’, ’30’], [‘sarah’, ‘smith’, ‘100’], [‘harry’, ‘harrington’, ‘5000’]]

Writing to CSV Files

Saving data to a CSV file is just as easy, you just need to :

  • open the file in append mode(or write mode of you want to replace the contents of the file!)
  • start the writer engine.
  • write the line you want to write
  • close the file to save it.