用于csv的Python编写器方法

时间:2014-01-27 06:23:06

标签: python csv

我在python中使用writerow方法编写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])

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

您需要正确打开文件(正如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也将为您处理文件的关闭。