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时,每条记录后都有一个额外的空行!

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


当前回答

我使用writerow

def write_csv(writer, var1, var2, var3, var4):
    """
    write four variables into a csv file
    """
    writer.writerow([var1, var2, var3, var4])      
        
numbers=set([1,2,3,4,5,6,7,2,4,6,8,10,12,14,16])
rules = list(permutations(numbers, 4))
#print(rules)
selection=[]
with open("count.csv", 'w',newline='') as csvfile:
    writer = csv.writer(csvfile)

    for rule in rules:
        number1,number2,number3,number4=rule
        if ((number1+number2+number3+number4)%5==0):
            #print(rule)
            selection.append(rule)
            write_csv(writer,number1,number2,number3,number4)

其他回答

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

with codecs.open( csv_file,  mode='w', encoding='utf-8') as out_csv:
     csv_out_file = csv.DictWriter(out_csv)
with open(destPath+'\\'+csvXML, 'a+') as csvFile:
    writer = csv.writer(csvFile, delimiter=';', lineterminator='\r')
    writer.writerows(xmlList)

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

简单的答案是csv文件应该总是以二进制模式打开,无论是输入还是输出,否则在Windows上就会出现行结束的问题。具体来说,在输出时,csv模块将写入\r\n(标准的csv行结束符),然后(在文本模式下)运行时将用\r\n (Windows标准的行结束符)替换\n,给出结果\r\r\n。

摆弄线终结者不是解决方案。

使用下面定义的方法将数据写入CSV文件。

open('outputFile.csv', 'a',newline='')

只需在open方法中添加一个额外的newline= "参数:

def writePhoneSpecsToCSV():
    rowData=["field1", "field2"]
    with open('outputFile.csv', 'a',newline='') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(rowData)

这将写入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