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

(andrew) #1
router1 is in Nashville and has IP 192.168.10.1.
router2 is in Tampa and has IP 192.168.20.1.
router3 is in San Jose and has IP 192.168.30.1.

If you want to add a fourth device to the CSV file, you can
follow a process very similar to what you did with text
files. Example 5-1 shows how to add a little interaction
from the command line to fill in the fields and create a
Python list with details on the new router. Instead using
of a reader object, this example uses a writer object to
store the formatted CSV data and then write it to the file.


Example 5-1 Code and Input for a CSV File

Click here to view code image


import csv
print("Please add a new router to the list")
hostname = input("What is the hostname? ")
ip = input("What is the ip address? ")
location = input("What is the location? ")
router = [hostname, ip, location]
with open("routerlist.csv", "a") as data:
csv_writer = csv.writer(data)
csv_writer.writerow(router)
<Below is interactive from the terminal after
running the above code>
Please add a new router to the list
What is the hostname? router4
What is the ip address? 192.168.40.1
What is the location? London

If you run the code shown in Example 5-1 and input
details for router 4, now when you display the router list,
you have the new router included as well:


Click here to view code image


router1 is in Nashville and has IP 192.168.10.1.
router2 is in Tampa and has IP 192.168.20.1.
Free download pdf