fir3net
PPS-Firenetbanner-780.5x190-30-03-17

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

 

Tags: Python

About the Author

RDonato

R Donato

Rick Donato is the Founder and Chief Editor of Fir3net.com. He currently works as a Principal Network Security Engineer and has a keen interest in automation and the cloud.

You can find Rick on Twitter @f3lix001