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

查看:111
本文介绍了使用 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)

应该可以.

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

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