使用 Python 编写 CSV 添加空行

我试图写到 CSV 文件,但有空白行之间。如何删除空白行?

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

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.

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

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

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

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

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

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.

Pyexcel works great with both Python2 and Python3 without troubles.

Fast installation with pip:

pip install pyexcel

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

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