CSV in Python adding an extra carriage return, on Windows

前端 未结 6 1076
慢半拍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:45

    While @john-machin gives a good answer, it's not always the best approach. For example, it doesn't work on Python 3 unless you encode all of your inputs to the CSV writer. Also, it doesn't address the issue if the script wants to use sys.stdout as the stream.

    I suggest instead setting the 'lineterminator' attribute when creating the writer:

    import csv
    import sys
    
    doc = csv.writer(sys.stdout, lineterminator='\n')
    doc.writerow('abc')
    doc.writerow(range(3))
    

    That example will work on Python 2 and Python 3 and won't produce the unwanted newline characters. Note, however, that it may produce undesirable newlines (omitting the LF character on Unix operating systems).

    In most cases, however, I believe that behavior is preferable and more natural than treating all CSV as a binary format. I provide this answer as an alternative for your consideration.

提交回复
热议问题