Reading CSV files
Some text files contain tabular data separated by commas. This is a convenient way of creating structured data, instead of using proprietary, more complex binary formats such as Excel or others. These files are called Comma Separated Values or CSV files, and most spreadsheet packages allow us to work directly with them.
Getting ready
We've prepared a CSV file using the data for the top 10 movies by theatre attendance, as described by this page: http://www.mrob.com/pub/film-video/topadj.html.
We copied the first 10 elements of the table into a spreadsheet program (Numbers) and exported the file as a CSV. The file is available in the GitHub repository in the Chapter04/documents
directory as top_films.csv
:
Figure 4.1: Content of the CSV file
How to do it...
- Import the
csv
module:>>> import csv
- Open the file, create a reader, and iterate through it to show the tabular data of all rows (only...