使用CSV lib,在Python中将连续数据附加到同一行 [英] Append continuous data to the same row using CSV lib, in Python
问题描述
这是我的代码:
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'])
此时,它会在新行中输出数据,因为它找到它。基本上,最终目标是生成一个包含一系列缺少Syslog和/或SNMP配置的主机名的CSV文件。我想要它的结尾是,例如:
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
正如你所看到的,并打印出主机名,那么,我目前的目标是:我想保持行打开,所以我可以继续追加更多的数据,因为if语句继续找到匹配。
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.
我试图在这个论坛和其他论坛上进行研究,但我不断发现如何追加CSV中的新行或我随机发现的评论,如何CSV库不支持添加新的列。
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)
这篇关于使用CSV lib,在Python中将连续数据附加到同一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!