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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With