python 生成csv 下载 内容换行_如何使用Python将换行符写为CSV到'\n'?

本文介绍如何修改代码,确保CSV文件中换行符以' '形式显示,并保持每一行独立。重点在于使用`utf-8`编码和正确设置`csv.writer`的`lineterminator`属性。

1586010002-jmsa.png

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])

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值