港股即時

Economic Calendar

Sunday, October 1, 2017

Python csv.writerow寫入多隔一行

用writerow 寫入時,每row 資料之間會多隔一行的情況。

原因是,在Windows系統下會幫每一行結尾多加一個看不見的"進位符號",然而這個動作writerow本身就會幫我們做,所以等於重複按Enter兩次。避免這種狀況一般常見的解決方法是以binary的方式開啟檔案:

f = open("xxx.csv","wb")
c = csv.writer(f)

然而這種方法在Python 3 下會產生錯誤:


ValueError: binary mode doesn't take a newline argument

在python 3的解決方法是,在後面多加一個參數

f = open('xxx.csv', 'w', newline='')

If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.


http://pykynix.blogspot.hk/2013/01/csvwriterow.html