{ File I/O with CSVs. }

Objectives:

By the end of this chapter, you should be able to:

  • Explain what a CSV file is
  • Read and write to CSV files

CSV with Python

Aside from reading text files, we can also read csv, or comma separated values. CSV files can be opened in a text editor or more commonly in programs like Microsoft Excel. CSVs are a common format for uploading and downloading data, so understanding how to programmatically work with them is important. Here is an example csv file:

pets.csv

name,type,age
Whiskey,dog,3
Moxie,cat,7
Mascis,dog,2

Most languages can actually support files that are separated by any character, not just commas (there is another format called tsv for tab separated values). Here is an example of a file that is separated by | (we call the character we separate by the "delimiter"):

file.csv

name|type|age
Whiskey|dog|3
Moxie|cat|7
Mascis|dog|2

Now, to read csv files, we'll need to import the csv module and use the csv.reader method. Let's take a look at an example.

Notice that the file we are reading in the example below,file.csv, is separated by |. Our next step is to read this file using the csv module:

import csv

with open('file.csv') as csvfile:
    reader = csv.reader(csvfile, delimiter='|')
    rows = list(reader)
    for row in rows:
        print(', '.join(row))

# name, type, age
# Whiskey, dog, 3
# Moxie, cat, 7
# Mascis, dog, 2

We can also create a dictionary for each row instead of a list, if we use the DictReader method:

import csv

with open('file.csv') as csvfile:
    reader = csv.DictReader(csvfile, delimiter='|')
    rows = list(reader)
    for row in rows:
        print(row)

# {'age': '3', 'name': 'Whiskey', 'type': 'dog'}
# {'age': '7', 'name': 'Moxie', 'type': 'cat'}
# {'age': '2', 'name': 'Mascis', 'type': 'dog'}        

Finally, we can also write to csv files in a similar way that we write to plain text files. But rather than creating a reader, you'll need to create a writer:

with open('file.csv', 'a') as csvfile:
    data_writer = csv.writer(csvfile, delimiter="|")
    data_writer.writerow(['Bojack','Horse','50'])

As before, you can also write using dictionaries instead of lists. Here's an example for a new csv that we're building from scratch.

with open('newfile.csv', 'a') as csvfile:
    data = ['name', 'fav_topic']
    writer = csv.DictWriter(csvfile, fieldnames=data)
    writer.writeheader() # this writes the first row with the column headings
    writer.writerow({
        'name': 'Elie',
        'fav_topic': 'Writing to CSVs!'     
    }) 

To learn more about working with CSVs in Python, you know what to do: check the docs!

When you're ready, move on to File I/O Exercises

Continue