用 Python 编写的 CSV 文件每行之间有空行 [英] CSV file written with Python has blank lines between each row

查看:30
本文介绍了用 Python 编写的 CSV 文件每行之间有空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

This code reads thefile.csv, makes changes, and writes results to thefile_subset1.

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

However, when I open the resulting csv in Microsoft Excel, there is an extra blank line after each record!

有没有办法让它不多放一个空行?

Is there a way to make it not put an extra blank line?

推荐答案

在 Python 2 中,使用 'wb' 而不是 'w' 模式打开 outfile.csv.writer 直接将 写入文件.如果你不以 binary 模式打开文件,它会写 因为在 Windows 上 text 模式会翻译每个 转化为 .

In Python 2, open outfile with mode 'wb' instead of 'w'. The csv.writer writes into the file directly. If you don't open the file in binary mode, it will write because on Windows text mode will translate each into .

在 Python 3 中,所需的语法发生了变化(请参阅下面的文档链接),因此请改为使用附加参数 newline=''(空字符串)打开 outfile.

示例:

In Python 3 the required syntax changed (see documentation links below), so open outfile with the additional parameter newline='' (empty string) instead.

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

文档链接

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆