使用Python写入CSV会添加空白行 [英] Writing to CSV with Python adds blank lines

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

问题描述

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

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

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


推荐答案

使用 csv 模块在Python 3中在几个方面改变的方式(docs),至少关于您需要如何打开该文件。无论如何,像

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)


b $ b

应该可以工作。

should work.

这篇关于使用Python写入CSV会添加空白行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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