1. 程式人生 > >Python3使用csv模組csv.writer().writerow()儲存csv檔案,產生空行的問題

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檔案,開啟檔案後,發現寫入的資料形式如下:


每一行資料後面都自動增加了一個空行。

該問題解決方法:在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 
來源:CSDN 
原文:https://blog.csdn.net/youzhouliu/article/details/53138661