如何使用Python将换行符写为'\ n'到csv? [英] How can Python be used to write line breaks to a csv as '\n'?
本文介绍了如何使用Python将换行符写为'\ n'到csv?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要重新定义以下代码,以便行数据中的任何换行符(将显示为空白行)在写入的文件中均显示为'\n'
.
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.
但是,需要在每行之后写'\n'
才能显示为空白行.
However, '\n'
needs to be written after each row to show up as a blank line.
每行显然都需要编码为'utf-8',以避免出现错误.
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'])
推荐答案
您需要使用replace
方法.
You need to manually replace newlines with \n
using the replace
method.
将 lineterminator
选项设置为所需的字符序列. 文档.
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])
这篇关于如何使用Python将换行符写为'\ n'到csv?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文