Python writerow method for csv



我正在使用Python中的作者方法来编写CSV文件中的值列表,并且在我添加的每一行之后,它一直在添加新行。如何停止添加新线路?以下是代码的块

for exception in tempList:
        statItem = (exception['count'],exception['stack'])
        locStatList.append(statItem)
        sortedStatTempList = sorted(locStatList, key=itemgetter(0), reverse=True)
        writer = csv.writer(open("temp",'w'),quotechar='x00')
        writer.writerow(["Server Name","JVM","Instance Exception"])
    for exception in sortedStattempList :
        s = str(exception[0])
        p = exception[1]
        tempVar = 'All Tomcat Servers'+','+s+','+p  
        writer.writerow([tempVar])

您应该使用二进制模式打开CSV文件(读取文档):

writer = csv.writer(open("temp",'wb'), quotechar='x00')

您需要正确打开文件(如Tim建议),但是您可以进一步优化代码:

with open('temp','wb') as f:
  writer = csv.writer(f, quotechar='x00')
  writer.writerow(["Server Name","JVM","Instance Exception"])
  for exception in sortedStattempList:
    tempVar = 'All Tomcat Servers,{},{}'.format(*exception)
    writer.writerow([tempVar])
  # or, you can do this
  lines = ['All Tomcat Servers,{},{}'.format(*e) for e in sortedStattempList]
  writer.writerows(lines) 

您应该避免串联字符串,而是使用formatjoinwith statement也将为您处理文件的关闭。

最新更新