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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With