用Python写的CSV文件每个之间有空行

2024-04-16 07:46:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

此代码读取thefile.csv,进行更改,并将结果写入thefile_subset1

但是,当我在Microsoft Excel中打开生成的csv时,每条记录后面都有一个额外的空行!

有没有办法让它不加空行?


Tags: csvinimportfordataaswithcounter
3条回答

在Python 3+中以二进制模式“wb”打开文件将不起作用。或者更确切地说,在编写数据之前,必须将其转换为二进制。那只是个麻烦。

相反,您应该将其保持为文本模式,但将换行符重写为空。就像这样:

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

在Python 2中,使用模式'wb'而不是'w'打开outfilecsv.writer直接将\r\n写入文件。如果您不在二进制模式下打开文件,它将写入\r\r\n,因为在Windows上,text模式将把每个\n转换为\r\n

在Python 3中,所需的语法已更改,因此使用附加参数newline=''打开outfile

示例:

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

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

文档链接

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

摆弄lineterminator不是解决办法。

相关问题 更多 >