用Python编写的CSV文件在每行之间都有空行

发布于 2021-02-02 23:22:47

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

有没有办法使它不放在多余的空白行?

关注者
0
被浏览
129
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    在Python 2中,请outfile使用模式'wb'而不是来打开'w'。该csv.writer写入\r\n直接到文件中。如果你未以二进制模式打开文件,它将写入,\r\r\n因为在Windows 文本模式下会将每个文件\n转换为\r\n

    在Python 3中,所需的语法已更改(请参见下面的文档链接),因此请改用outfile其他参数newline=''(空字符串)打开。

    例子:

    # 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)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看