CSV in Python adding an extra carriage return, on Windows

前端 未结 6 1078
慢半拍i
慢半拍i 2020-11-22 07:14
import csv
outfile = file(\'test.csv\', \'w\')
writer = csv.writer(outfile, delimiter=\',\', quoting=csv.QUOTE_MINIMAL)
writer.writerow([\'hi\',\'dude\'])
writer.wri         


        
6条回答
  •  余生分开走
    2020-11-22 07:43

    In Python 3 (I haven't tried this in Python 2), you can also simply do

    with open('output.csv','w',newline='') as f:
        writer=csv.writer(f)
        writer.writerow(mystuff)
        ...
    

    as per documentation.

    More on this in the doc's footnote:

    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.

提交回复
热议问题