Using the CSV module to read CSV data
In this first demonstration, you will read the artificial_roads_by_region.csv
file and get an estimate of the total length of roads as of 2011.
The first step to using the CSV module is to import the module, as shown in the following example:
import csv
The next step, similar to the process use in Chapter 3, Reading, Exploring, and Modifying Data - Part I, is to open the file containing the data. Recall that for this chapter, the code is one directory up from the base directory. This means that in the path to the data, you will first need to go back one directory using ../
in macOS and Linux or ..\\
in Windows. In the following demonstration, I've created a Python script called csv_intro.py
in which the open()
function is used to open artificial_roads_by_region.csv
with read permission:
import csv
## open the file containing the data
fin = open("../data/input_data/artificial_roads_by_region.csv","r",newline="")
Note
You may have noticed that a new parameter...