使用 Python 写入 CSV 添加空行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14693646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:10:05  来源:igfitidea点击:

Writing to CSV with Python adds blank lines

pythoncsvpython-3.3

提问by user2031063

I am trying to write to CSV file but there are blank rows in between. How can I remove the blank rows?

我正在尝试写入 CSV 文件,但中间有空白行。如何删除空白行?

import csv
b = open('test.csv', 'w')
a = csv.writer(b)
data = [['Me', 'You'],\
        ['293', '219'],\
        ['54', '13']]
a.writerows(data)
b.close()

采纳答案by DSM

The way you use the csvmodule changed in Python 3 in several respects (docs), at least with respect to how you need to open the file. Anyway, something like

csv在 Python 3 中使用模块的方式在几个方面(docs) 发生了变化,至少在您需要如何打开文件方面是这样。无论如何,像

import csv
with open('test.csv', 'w', newline='') as fp:
    a = csv.writer(fp, delimiter=',')
    data = [['Me', 'You'],
            ['293', '219'],
            ['54', '13']]
    a.writerows(data)

should work.

应该管用。

回答by Wilduck

If you're using Python 2.x on Windows you need to change your line open('test.csv', 'w')to open('test.csv', 'wb'). That is you should open the file as a binary file.

如果您在 Windows 上使用 Python 2.x,则需要将行更改open('test.csv', 'w')open('test.csv', 'wb'). 也就是说,您应该将文件作为二进制文件打开

However, as stated by others, the file interface has changed in Python 3.x.

然而,正如其他人所说,文件接口在 Python 3.x 中发生了变化。

回答by Aditya

You need to open the file in binary bmode to take care of blank lines in Python 2. This isn't required in Python 3.

您需要以二进制b模式打开文件以处理 Python 2 中的空行。这在 Python 3 中不是必需的。

So, change open('test.csv', 'w')to open('test.csv', 'wb').

因此,更改open('test.csv', 'w')open('test.csv', 'wb').

回答by John Smith

import csv

hello = [['Me','You'],['293', '219'],['13','15']]
length = len(hello[0])

with open('test1.csv', 'wb') as testfile:
    csv_writer = csv.writer(testfile)
    for y in range(length):
        csv_writer.writerow([x[y] for x in hello])

will produce an output like this

将产生这样的输出

Me You
293 219
13 15

Hope this helps

希望这可以帮助

回答by Danny Lessio

Pyexcelworks great with both Python2 and Python3 without troubles.

Fast installation with pip:

Pyexcel适用于 Python2 和 Python3,没有任何问题。

使用 pip 快速安装:

pip install pyexcel

After that, only 3 lines of code and the job is done:

之后,只需要3行代码,工作就完成了:

import pyexcel
data = [['Me', 'You'], ['293', '219'], ['54', '13']]
pyexcel.save_as(array = data, dest_file_name = 'csv_file_name.csv')