Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Python be used to write line breaks to a csv as '\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.

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'])
like image 766
Phillip Avatar asked Dec 14 '16 03:12

Phillip


1 Answers

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])
like image 155
Jeff Mercado Avatar answered Sep 18 '22 17:09

Jeff Mercado