
I need to redefine the following code so that any line breaks in the row data (that would show up as a blank line) show as '\n' in the written file.
However, '\n' needs to be written after each row to show up as a blank line.
Each row apparently needs to be encoded as 'utf-8' to avoid errors.
with open('csvfile.csv', 'w') as csvOutput:
testData = csv.writer(csvOutput, delimiter='|', escapechar=' ', quoting=csv.QUOTE_NONE)
for row in data:
newRow = [row[x].encode('utf-8') for x in xrange(len(row))]
testData.writerow(newRow)
testData.writerow(['\n'])
解决方案
You need to manually replace newlines with \n using the replace method.
Set the lineterminator option to the desired character sequence. More info on what else is available is in the docs.
with open('csvfile.csv', 'w') as csvOutput:
writer = csv.writer(csvOutput, delimiter='|', escapechar=' ', quoting=csv.QUOTE_NONE, lineterminator='\n')
for row in data:
writer.writerow([s.replace('\n', '\\n').encode('utf-8') for s in row])
本文介绍如何修改代码,确保CSV文件中换行符以'
'形式显示,并保持每一行独立。重点在于使用`utf-8`编码和正确设置`csv.writer`的`lineterminator`属性。

被折叠的 条评论
为什么被折叠?



