Python3使用csv模块csv.writer().writerow()保存csv文件,产生空行的问题

本文介绍使用csv.writer()写入CSV文件时,每行数据后出现多余空行的问题及解决方案。通过在open()函数中添加newline=''参数,可以避免此问题,确保CSV文件正确格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:csv.writer().writerow()保存的csv文件,打开时每行后都多一行空行

一开始的代码如下:


def write_csv_file(path, head, data):
    try:
        with open(path, 'w') as csv_file:
            writer = csv.writer(csv_file, dialect='excel')
 
            if head is not None:
                writer.writerow(head)
 
            for row in data:
                writer.writerow(row)
 
            print("Write a CSV file to path %s Successful." % path)
    except Exception as e:
        print("Write an CSV file to path: %s, Case: %s" % (path, e))

调用该方法将数据写入csv文件,打开文件后,发现写入的数据形式如下:


每一行数据后面都自动增加了一个空行。

该问题解决方法:在open()内增加一个参数newline='' 即可,更改后代码结构如下:


def write_csv_file(path, head, data):
    try:
        with open(path, 'w', newline='') as csv_file:
            writer = csv.writer(csv_file, dialect='excel')
 
            if head is not None:
                writer.writerow(head)
 
            for row in data:
                writer.writerow(row)
 
            print("Write a CSV file to path %s Successful." % path)
    except Exception as e:
        print("Write an CSV file to path: %s, Case: %s" % (path, e))

重新执行该程序后,得到了想要的结果,结果如下:

--------------------- 
作者:youzhouliu 
来源:优快云 
原文:https://blog.youkuaiyun.com/youzhouliu/article/details/53138661 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值