用于csv的Python writerow方法

用于csv的Python writerow方法,python,csv,Python,Csv,我在python中使用writerow方法在csv文件中写入值列表,它在我添加的每一行之后不断添加新行。如何停止添加新行?下面是一段代码 for exception in tempList: statItem = (exception['count'],exception['stack']) locStatList.append(statItem) sortedStatTempList = sorted(locStatList, key=item

我在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])

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


您需要正确打开文件(正如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) 

应避免串接字符串,而应使用
格式
连接
with语句也将为您处理文件的关闭。

您能再解释一下吗?打开文件要写入的行是什么?哪个Python版本?
writerow
将写入行。:)。因此,它将添加新行字符以分隔两行。我使用的版本是2.4.3。我尝试删除“[]”,但o/p类似于A、l、l、T、o、m、c、A、T。。。。。这不是我们想要的output@MatkuJain:啊,是的,我误读了那句话。但是关于二进制模式的建议仍然有效…二进制模式也已完成,但它仍然有效。因此,CSV文件的每一行之间都有一条空行?是的,每一行之间都有一条空行,我需要删除该空文件。我尝试了上述解决方案,但它仍然有效,不断出现语法错误。同时也给出了tempVar的错误,即“AttributeError:'str'对象没有属性'format'”“您使用的Python版本是什么?我使用的版本是2.4.3。”
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)