Importing data from CSV
In this recipe we will work with the most common file format that one will encounter in the wild world of data, CSV. It stands for Comma Separated Values, which almost explains all the formatting there is. (There is also a header part of the file, but those values are also comma separated.)
Python has a module called csv
that supports reading and writing CSV files in various dialects. Dialects are important because there is no standard CSV and different applications implement CSV in slightly different ways. A file's dialect is almost always recognizable by the first look into the file.
Getting ready
What we need for this recipe is the CSV file itself. We will use sample CSV data that you can download from ch02-data.csv
.
We assume that sample datafiles is in the same folder as the code reading it.
How to do it...
The following code example demonstrates how to import data from a CSV file. We will:
Open the
ch02-data.csv
file for reading.Read the header first.
Read the rest...