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

(andrew) #1

In this example, you now have a list of lists that includes
each row of data. If you wanted to manipulate this data,
you could because it’s now in a native format for Python.
Using list notation, you can extract individual pieces of
information:


Click here to view code image


>>> sampledata[0]
['router1', '192.168.10.1', 'Nashville']
>>> sampledata[0][1]
'192.168.10.1'

Using with, you can iterate through the CSV data and
display information in an easier way:


Click here to view code image


import csv

with open("routerlist.csv") as data:
csv_list = csv.reader(data)
for row in csv_list:
device = row[0]
location = row[2]
ip = row[1]
print(f"{device} is in {location.rstrip()}
and has IP
{ip}.")

Notice the rstrip function used to format the location
variable? You use it because the last entry in your CSV
file will have a whitespace character at the very end when
it is read into Python because it is at the very end of the
file. If you don’t get rid of it (by using rstrip), your
formatting will be off.


The output of this code is as follows:


Click here to view code image

Free download pdf