CSV in Python adding an extra carriage return, on

2019-01-01 03:30发布

In Python 2.7 running on Windows XP pro:

import csv
outfile = file('test.csv', 'w')
writer = csv.writer(outfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['hi','dude'])
writer.writerow(['hi2','dude2'])
outfile.close()

It generates a file, test.csv, with an extra \r at each row, like so:

test.csv

hi,dude\r\r\nhi2,dude2\r\r\n

instead of the expected:

hi,dude\r\nhi2,dude2\r\n

Why is this happening, or is this actually the desired behavior?

7条回答
不流泪的眼
2楼-- · 2019-01-01 04:19

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.

查看更多
登录 后发表回答