Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python csv.writer - is it possible to write to a variable?

Tags:

python

Is it possible to use csv.writer to write data to a variable rather than a file?

I was hoping I could do something like this:

data = ''
csv.writer(data)
# ...... (I have removed the csv processing code for brevity)
message = EmailMessage('Invoice for 2012', 'h', '[email protected]', ['[email protected]'])
message.attach('invoice.csv', data, 'text/csv')
message.send()

When I execute the code I get the following error:

   argument 1 must have a "write" method
like image 795
Imran Azad Avatar asked Sep 01 '12 14:09

Imran Azad


3 Answers

The csv.writer class needs a file-like object, something with a .write() method. A StringIO class would be best here:

from cStringIO import StringIO

data = StringIO()
csv.writer(data)
# write your stuff
message = EmailMessage('Invoice for 2012', 'h', '[email protected]', ['[email protected]'])
message.attach('invoice.csv', data.getvalue(), 'text/csv')
message.send()

I used the C-variant of the StringIO module there; the advantage is speed, the disadvantage that you can use each instance only as a writable or a readable file. Since all you do is write to it before retrieving the written data, that's just fine.

like image 186
Martijn Pieters Avatar answered Oct 07 '22 04:10

Martijn Pieters


You can always use StringIO whenever you need a file-like object (with a write method) and do not want to create an actual file in the filesystem.

An advantage of this memory-file approach is that I/O is much faster than with a real storage backend. If you want to be even faster, you can use cStringIO. Note that cStringIO is not always available, so you could do something like

try:
    import cStringIO as StringIO
except ImportError:
    import StringIO
like image 31
Dr. Jan-Philip Gehrcke Avatar answered Oct 07 '22 05:10

Dr. Jan-Philip Gehrcke


Python 3.x and 2.6+

cStringIO as described in the other answers has been removed in Python 3.

Instead use io.StringIO like this:

import csv
import io

mem_file = io.StringIO()
writer = csv.writer(mem_file)

writer.writerow(['your', 'data', 'here'])

print(mem_file.getvalue())

your,data,here

like image 30
Hubert Grzeskowiak Avatar answered Oct 07 '22 03:10

Hubert Grzeskowiak