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

问题: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文件,打开文件后,发现写入的数据形式如下:

《Python3使用csv模块csv.writer().writerow()保存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))  
        

重新执行该程序后,得到了想要的结果,结果如下:
《Python3使用csv模块csv.writer().writerow()保存csv文件,产生空行的问题》

    原文作者:炎泽
    原文地址: https://segmentfault.com/a/1190000011139566
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞