Python csv.writer - is it possible to write to a variable?
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.
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
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