Here is my code:
import csv
with open(outputfile, 'a') as csvfile:
filewrite = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
filewrite.writerow([hostname])
if (CiscoSyslog == 0):
filewrite.writerow(['Syslog'])
if (CiscoSNMP == 0):
filewrite.writerow(['SNMP'])
At the moment, it outputs data in a new row, as it finds it. Basically, the ultimate goal is to generate a CSV file with bunch of hostnames that are missing Syslog and/or SNMP configuration. The way I want it to look in the end is, for example:
router1,Syslog
router2,SNMP
router3,Syslog,SNMP
As you can see, at the begging I have the file open and it prints out the hostname, then, my goal at the moment is: I would like to keep the row "open", so I can keep appending more data as the "if" statements keep finding a match. And ultimately it produces something similar to the example I have shown above.
I tried researching on this forum, and other forums, but I keep finding examples of how to append to a new row in CSV, or I keep finding comments by random people, how CSV library does not support adding a new column.
Some help would be very much appreciated. Thank you!
解决方案
You're going to want to construct your row entirely before trying to write it. Try this:
import csv
with open(outputfile, 'a') as csvfile:
filewrite = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
row = [hostname]
if (CiscoSyslog == 0):
row.append('Syslog')
if (CiscoSNMP == 0):
row.append('SNMP')
filewrite.writerow(row)