DevNet Associate DEVASC 200-901 Official Certification Guide by Adrian Iliesiu (z-lib.org)

(andrew) #1

Each line in a CSV file represents a row, and commas are
used to separate the individual data fields to make it
easier to parse the data. Python has a built-in CSV
module that you can import that understands the CSV
format and simplifies your code. The following is an
example of a typical CSV file (in this case named
routerlist.csv):


Click here to view code image


"router1","192.168.10.1","Nashville"
"router2","192.168.20.1","Tampa"
"router3","192.168.30.1","San Jose"

This example shows a common asset list or device
inventory, such as one that you might pull from a
network management system or simply keep track of
locally. To start working with this data, you have to
import the CSV module, and then you need to create a
reader object to read your CSV file into. You first have
to read the file into a file handle, and then you run the
CSV read function on it and pass the results on to a
reader object. From there, you can begin to use the CSV
data as you wish. You can create another variable and
pass the reader object variable to the built-in list()
function. Here is what the code would look like:


Click here to view code image


>>> import csv
>>> samplefile = open('routerlist.csv')
>>> samplereader = csv.reader(samplefile)
>>> sampledata = list(samplereader)
>>> sampledata
[['router1', '192.168.10.1', 'Nashville'],
['router2',
'192.168.20.1', 'Tampa'], ['router3',
'192.168.30.1', 'San Jose ']]
Free download pdf