我在编写一个python脚本时遇到了一点小麻烦,我正在编写这个脚本来审核我公司许多不同应用程序中的所有CSV文件,我几乎完成了一个概念证明,带到老板面前,展示我能用python做些什么,但问题是我对python中的CSV类没有那么好的理解。。。。你知道吗
以下是我的计算机信息列表的示例:
['EB-ABORTZ,True,False,False,0', 'EB-AGONCHAROVA,True,False,False,0',
'EB-AHART-1,True,False,False,0', 'EB-AHEIDENREICH,True,False,False,0',
'EB-ALOCKLEAR,True,False,False,0', 'EB-AMARGULIS,True,False,False,0',
'EB-ASKLAR,True,False,False,0', 'EB-ASKLAR-1,True,False,False,0',
'EB-ASKLAR-3,True,False,False,0', 'EB-BCHOW-1,True,False,False,0',
'EB-BJOHNSON,True,False,False,0', 'EB-BLYLE,True,False,False,0',
'EB-BRUSSUM,True,False,False,0', 'EB-CCLEARY,True,False,False,0',
'EB-...]
下面是一个例子,代码最后会产生什么。。。。。你知道吗
"E","B","-","A","B","O","R","T","Z",",","T","r","u","e",",","F","a","l","s","e",",","F","a","l","s","e",",","0"
"E","B","-","A","G","O","N","C","H","A","R","O","V","A",",","T","r","u","e",",","F","a","l","s","e",",","F","a","l","s","e",",","0"
"E","B","-","A","H","A","R","T","-","1",",","T","r","u","e",",","F","a","l","s","e",",","F","a","l","s","e",",","0"
"E","B","-","A","H","E","I","D","E","N","R","E","I","C","H",",","T","r","u","e",",","F","a","l","s","e",",","F","a","l","s","e",",","0"
"E","B","-","A","L","O","C","K","L","E","A","R",",","T","r","u","e",",","F","a","l","s","e",",","F","a","l","s","e",",","0"
"E","B","-","A","M","A","R","G","U","L","I","S",",","T","r","u","e",",","F","a","l","s","e",",","F","a","l","s","e",",","0"
下面是我用来在事后将数据导出为CSV格式的方法的副本。你知道吗
def collate_computers(computers):
with open('results.csv', 'w', encoding='utf8', )as outfile:
writer = csv.writer(outfile, quoting=csv.QUOTE_ALL, delimiter=',')
for c in computers:
writer.writerow(c)
CSV writer函数
writerow
将一个列表作为输入,并将每个元素写入行中。将单个字符串传递给函数时,编写器将该字符串解释为字符列表。你知道吗我假设您希望按字符串中显示的方式写入每一行。所以不要使用
writer.writerow(c)
,而是使用writer.writerow(c.split(','))
。这会将字符串拆分为一个列表,列表中用逗号分隔。你知道吗您的csv文件应如下所示:
按原样,write rows方法生成逗号分隔的值(.csv)
如果希望每行1个字符串(即每行1个列表项)
问题是
computers
中的每个项都是一个字符串,而Python中的字符串是字符序列,因此writer.writerow()
认为每个字符都是一个单独的字段。要解决这个问题,需要首先根据逗号所在的位置将每个字符串split
放入字段:results.csv
相关问题 更多 >
编程相关推荐