Reading CSV files using Python 3 is what you will learn in this article. The file data contains comma separated values (csv). The comma is known as the delimiter, it may be another character such as a semicolon.
Complete Python Bootcamp: Go from zero to hero in Python
An example csv file:
The process will be:
Read CSV file
The most basic method to read a csv file is:
We import the csv module. We read every row in the file. Every row is returned as an array and can be accessed as such, to print the first cells we could simply write:
We would want to have the data in arrays, we can achieve that using:
We creates two arrays: dates and scores. We use the append method to add the cells to the arrays.
If you want to use a different delimiter simply change the reader call:
Load CSV function
If you have many files in an identical format, you can create a function for loading the data:
Given a filename, the function will read and parse the csv data. Its added to the arrays dates and scores and returned.