import csv

with open('thefile.csv', 'rb') as f:
  data = list(csv.reader(f))
  import collections
  counter = collections.defaultdict(int)

  for row in data:
        counter[row[10]] += 1


with open('/pythonwork/thefile_subset11.csv', 'w') as outfile:
    writer = csv.writer(outfile)
    for row in data:
        if counter[row[10]] >= 504:
           writer.writerow(row)

这段代码读取file.csv,进行修改,并将结果写入到file_subset1。

然而,当我在Microsoft Excel中打开结果csv时,每条记录后都有一个额外的空行!

有没有办法让它不放额外的空行?


当前回答

with open(destPath+'\\'+csvXML, 'a+') as csvFile:
    writer = csv.writer(csvFile, delimiter=';', lineterminator='\r')
    writer.writerows(xmlList)

lineterminator='\r'"允许传递到下一行,两行之间没有空行。

其他回答

csv。Writer模块直接控制行结束符,并直接将\r\n写入文件。在python3中,该文件必须以非翻译文本模式打开,参数为'w', newline= "(空字符串),否则在Windows上将写入\r\r\n,其中默认文本模式将每个\n转换为\r\n。

#!python3
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)

在Python 2中,使用二进制模式以'wb'而不是'w'模式打开outfile,以防止Windows换行符转换。Python 2在Unicode方面也有问题,需要其他变通方法来编写非ascii文本。如果你必须处理在Python 2上将Unicode字符串写入csv,请参阅下面的Python 2链接以及页面末尾的unicoderreader和UnicodeWriter示例,或者查看第三方unicodecsv模块:

#!python2
with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile:
    writer = csv.writer(outfile)

文档链接

https://docs.python.org/3/library/csv.html#csv.writer https://docs.python.org/2/library/csv.html#csv.writer

在使用Python 3时,可以通过使用codecs模块来避免空行。正如文档中所述,文件是以二进制模式打开的,因此不需要更改换行符kwarg。我最近遇到了同样的问题,这对我来说很有效:

with codecs.open( csv_file,  mode='w', encoding='utf-8') as out_csv:
     csv_out_file = csv.DictWriter(out_csv)

借用这个答案,似乎最干净的解决方案是使用io.TextIOWrapper。我为自己解决了这个问题:

from io import TextIOWrapper

...

with open(filename, 'wb') as csvfile, TextIOWrapper(csvfile, encoding='utf-8', newline='') as wrapper:
    csvwriter = csv.writer(wrapper)
    for data_row in data:
        csvwriter.writerow(data_row)

上面的答案与Python 2不兼容。为了具有兼容性,我认为只需要将所有的写入逻辑包装在if块中:

if sys.version_info < (3,):
    # Python 2 way of handling CSVs
else:
    # The above logic

从最初的问题开始的十年里,许多其他的答案都已经过时了。对于Python3,答案在文档中是正确的:

如果csvfile是一个文件对象,它应该用newline= "

脚注更详细地解释了:

如果没有指定newline= ",则内嵌在带引号字段中的换行符将不能被正确解释,并且在write时使用\r\n linend的平台上将添加一个额外的\r。指定newline= "应该总是安全的,因为csv模块有自己的(通用的)换行处理。

with open(destPath+'\\'+csvXML, 'a+') as csvFile:
    writer = csv.writer(csvFile, delimiter=';', lineterminator='\r')
    writer.writerows(xmlList)

lineterminator='\r'"允许传递到下一行,两行之间没有空行。