How do I create a multiline cell based CSV file within Python ?

Within this short tutorial we will show you the steps required to create a csv file that includes multi-line cells within Python.

In order to create a mutliline cell within Excel (2010/2013) the following is required:

  1. newlines are represented with a carriage return/newline,
  2. the string should be wrapped in quotes.

One of the great things with the Python csv module is it takes care of the quotes for you. Below provides an example,

#!/usr/bin/env python2.7

import csv

multiline_string = "this\nis\nsome\ntext"                # assign string
multiline_string = multiline_string.replace('\n','\r\n') # convert newlines to newlines+carriage return

with open('xyz.csv', 'wb') as outfile:
      w = csv.writer(outfile)                            # assign csv writer method
      w.writerow(['sometext',multiline_string])          # append/write row to file


Rick Donato

Want to become a programming expert?

Here is our hand-picked selection of the best courses you can find online:
Python Zero to Hero course
Python Pro Bootcamp
Bash Scripting and Shell Programming course
Automate with Shell Scripting course
The Complete Web Development Bootcamp course
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial