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', 'noreply@test.co.uk', ['test@test.co.uk'])
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.writerclass needs a file-like object, something with a.write()method. AStringIOclass would be best here:I used the C-variant of the
StringIOmodule 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.